两个itertools生成器的组合

2024-10-03 04:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个生成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,2,3,a,b],[1,2,3,a,b],[1,2,3,a,c],[1,2,3,b,c]。你知道吗

我不能从itertools组合中列出一个列表,因为真正的数据集列表要大得多。有人想知道如何把两种工具结合起来吗?你知道吗


Tags: inimport列表forreturndefanyall
1条回答
网友
1楼 · 发布于 2024-10-03 04:30:24

如果要迭代组合,可以执行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 

相关问题 更多 >