Given a list as follows:
[(1, 2), (3, 4, 5), (6,)]
I know it's very easy to combine the list of tuples by using itertools.
(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)
But how can I solve it without using itertools?
Given a list as follows:
[(1, 2), (3, 4, 5), (6,)]
I know it's very easy to combine the list of tuples by using itertools.
(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)
But how can I solve it without using itertools?
[(x, y, 6) for x in (1, 2) for y in (3, 4, 5)]
Also see Get the cartesian product of a series of lists? for more general solutions
Here's a fairly generic approach with a series of loops over the input:
lst = [(1, 2), (3, 4, 5), (6,)]
result = [tuple([l]) for l in lst[0]]
for l in lst[1:]:
out = []
for r in result:
for i in range(len(l)):
out.append((*r, l[i]))
result = out
print(result)
Output:
[(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)]
def product(pools):
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
return result
product([(1,2,3),(4,5),(6,)])
[[1, 4, 6], [1, 5, 6], [2, 4, 6], [2, 5, 6], [3, 4, 6], [3, 5, 6]]