【问题标题】:Combinations from two itertools generators来自两个 itertools 生成器的组合
【发布时间】:2019-10-14 13:00:42
【问题描述】:

我有两个列表,从中生成 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 组合中列出列表,因为真正的数据集列表要大得多。有没有人想过如何结合使用两个迭代工具?

【问题讨论】:

  • 请注意,generator 是 Python 中的特定类型,即使用 yield 表达式的函数返回的事物的类型。您称为生成器的一般事物是迭代器。每个generator 值都是一个迭代器,但并非所有迭代器都是generator 的实例。

标签: python pandas combinations itertools


【解决方案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 

【讨论】:

  • 感谢我在这两种组合中苦苦挣扎,但链条确实可以解决问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
相关资源
最近更新 更多