我有两个列表,可从中从以下列表中生成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)
现在,我想从
combinationList1
和combinationList2
进行所有可能的组合,以使所需的输出为:[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结合使用?
最佳答案
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