Combinations from two itertools generators

Viewed 171

I have two lists from where I generate itertools generators from as following:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

import itertools

def all_combinations(any_list):
    return itertools.chain.from_iterable(
        itertools.combinations(any_list, i + 1)
        for i in range(len(any_list)))

combinationList1 = all_combinations(list1)
combinationList2 = itertools.combinations(list2, 2)

With the following code I can find the combinations:

for j in combinationList1:
   print(j)

Now I would like to make all possible combinations from combinationList1 and combinationList2 so that the desired output would be: [1,a,b], [1,a,c], [1,b,c], ....., [1,2,3,a,b], [1,2,3,a,c],[1,2,3,b,c].

I can't make a list from the itertools combinations since the real dataset lists are way bigger. Anyone thoughts on how to take the combination of two itertools?

1 Answers

If you want to iterate over the combination, you could do product + chain:

for j in itertools.product(combinationList1, combinationList2):
    for e in itertools.chain.from_iterable(j):
        print(e, end=" ")
    print()

Output

1 a b 
1 a c 
1 b c 
2 a b 
2 a c 
2 b c 
3 a b 
3 a c 
3 b c 
1 2 a b 
1 2 a c 
1 2 b c 
1 3 a b 
1 3 a c 
1 3 b c 
2 3 a b 
2 3 a c 
2 3 b c 
1 2 3 a b 
1 2 3 a c 
1 2 3 b c 
Related