来自两个itertools生成器的组合

问题描述 投票:1回答:1

我有两个列表,可从中从以下列表中生成itertools生成器:

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)

使用以下代码,我可以找到组合:

for j in combinationList1:
   print(j)

现在,我想对combinationList1combinationList2进行所有可能的组合,以使所需的输出为:[1,a,b],[1,a,c],[ 1,b,c],.....,[1,2,3,a,b],[1,2,3,a,c],[1,2,3,b,c]

我无法从itertools组合中创建列表,因为实际的数据集列表要大得多。是否有人想到如何将两个itertools结合使用?

python pandas combinations itertools
1个回答
1
投票

如果要迭代组合,可以执行product + chain

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

输出

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 
© www.soinside.com 2019 - 2024. All rights reserved.