我有下面的代码。此代码提供了list1和list2之间的所有可能组合。
import itertools
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
print(list(itertools.product(list1, list2)))
Output:
[(1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10)]
我想要的是从list1中获得2个值和从list2中获得3个值的所有可能组合(没有重复(。所以可能的输出应该如下。我该怎么做?
[(1,2,6,7,8), (1,2,7,8,9), (1,2,8,9,10), (2,3,6,7,8), and so on.......]
以下操作即可:
from itertools import combinations as com, product as prod
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
[c1 + c2 for c1, c2 in prod(com(list1, 2), com(list2, 3))]
# [(1, 2, 6, 7, 8),
# (1, 2, 6, 7, 9),
# (1, 2, 6, 7, 10),
# ...
# (4, 5, 7, 9, 10),
# (4, 5, 8, 9, 10)]
这就生成了两个列表中各个组合的笛卡尔乘积,并简单地连接每一对以避免嵌套元组。
您需要首先为每个列表构建所需的组合,然后进行产品,您还需要加入产品((1, 2), (6, 7, 8)) => (1, 2, 6, 7, 8)
的内部结果
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
c1 = combinations(list1, r=2)
c2 = combinations(list2, r=3)
print(list(map(lambda x: tuple(chain(*x)), product(c1, c2)))) # [(1, 2, 6, 7, 8), (1, 2, 6, 7, 9), (1, 2, 6, 7, 10), (1, 2, 6, 8, 9), (1, 2, 6, 8, 10), (1, 2, 6, 9, 10), (1, 2, 7