猿问

蟒蛇在两个名单上。从每个列表中获取大于 1 的值

我有下面的代码。此代码给出了 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.......]


慕姐8265434
浏览 89回答 2
2回答

蝴蝶刀刀

以下操作即可:from itertools import combinations as com, product as prodlist1 = [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
随时随地看视频慕课网APP

相关分类

Python
我要回答