BubaSkrimp
BubaSkrimp

Reputation: 63

Combining 2 itertools product lists for a larger combination to find all combinations

Basically I am trying to reduce the number of combinations using itertools.product but get all combinations from the 4 elements using 2 lists.

I am able to create the 2 separate element lists of combinations but I cannot figure out how to combine the 2 list getting all combinations of them.

import itertools
pos_vars = ('a', 'b')
pos_num = (1, 0.5, 0)
neg_vars = ('c', 'd')
neg_num = (-1, -0.5, 0)
pos = [list(zip(pos_vars, p)) for p in itertools.product(pos_num, repeat=2)]
print(pos)
[[('a', 1), ('b', 1)], [('a', 1), ('b', 0.5)], [('a', 1), ('b', 0)], [('a', 0.5), ('b', 1)], [('a', 0.5), ('b', 0.5)], [('a', 0.5), ('b', 0)], [('a', 0), ('b', 1)], [('a', 0), ('b', 0.5)], [('a', 0), ('b', 0)]]

neg = [list(zip(neg_vars, n)) for n in itertools.product(neg_num, repeat=2)]
print(neg)
[[('c', -1), ('d', -1)], [('c', -1), ('d', -0.5)], [('c', -1), ('d', 0)], [('c', -0.5), ('d', -1)], [('c', -0.5), ('d', -0.5)], [('c', -0.5), ('d', 0)], [('c', 0), ('d', -1)], [('c', 0), ('d', -0.5)], [('c', 0), ('d', 0)]]

The combined list from both lists should look something like: [[('a', 1), ('b', 1), ('c', -1), ('d', -1)], [('a', 1), ('b', 1), ('c', -1), ('d', -0.5)], etc.]

I am able to get the full range but am basically doubling the computations which I am trying to avoid using the below code:

full_var = ('a', 'b', 'c', 'd')
full_num = (-1, -0.5, 0, 0.5, 1)
full = [list(zip(full_var, f)) for f in itertools.product(full_num, repeat=4)]

Thanks in advance!

Update - I was able to get my 81 combinations. Not the most efficient coding but it works and can be improved upon.

pos_a_var = ('a')
pos_b_var = ('b')
neg_c_var = ('c')
neg_d_var = ('d')
pos_num = (1, 0.5, 0)
neg_num = (-1, -0.5, 0)
pos_a = list(itertools.product(pos_a_var, pos_num))
pos_b = list(itertools.product(pos_b_var, pos_num))
neg_c = list(itertools.product(neg_c_var, neg_num))
neg_d = list(itertools.product(neg_d_var, neg_num))
comb_list = [pos_a, pos_b, neg_c, neg_d]
all_combinations = list(itertools.product(*comb_list))
len(all_combinations)
81

Still working on making this code a bit cleaner.

Upvotes: 0

Views: 691

Answers (1)

U13-Forward
U13-Forward

Reputation: 71580

Maybe:

print([x + y for x, y in zip(pos, neg)])

Output:

[[('a', 1), ('b', 1), ('c', -1), ('d', -1)], [('a', 1), ('b', 0.5), ('c', -1), ('d', -0.5)], [('a', 1), ('b', 0), ('c', -1), ('d', 0)], [('a', 0.5), ('b', 1), ('c', -0.5), ('d', -1)], [('a', 0.5), ('b', 0.5), ('c', -0.5), ('d', -0.5)], [('a', 0.5), ('b', 0), ('c', -0.5), ('d', 0)], [('a', 0), ('b', 1), ('c', 0), ('d', -1)], [('a', 0), ('b', 0.5), ('c', 0), ('d', -0.5)], [('a', 0), ('b', 0), ('c', 0), ('d', 0)]]

Upvotes: 1

Related Questions