Python Itertools 为每个组合添加列表

Python Itertools Add List for Every Combination

我需要为 list1 创建每个组合,但将 list2 添加到 list1 的每个组合。

例如,这会为 list1 的每个值创建一个组合:

list1 = ["a", "b" , "c"]
list2 = ["d", "e"]
list(itertools.combinations(list1, 2))
[('a', 'b'), ('a', 'c'), ('b', 'c')]

但我希望结果是:

[('a', 'b', 'd', 'e'), ('a', 'c'', d', 'e'), ('b', 'c', 'd', 'e')]

我已经尝试了这些常用方法,但得到了不理想的结果:

list1 = ["a", "b" , "c"]
list2 = ["d", "e"]
print(list(itertools.combinations(list1, 2)).extend(list2))
None

print(list(itertools.combinations(list1, 2)) + list2)
[('a', 'b'), ('a', 'c'), ('b', 'c'), 'd', 'e']

print(list(itertools.combinations(list1, 2) + list2))
TypeError: unsupported operand type(s) for +: 'itertools.combinations' and 'list'

如有任何帮助,我们将不胜感激。谢谢。

您可以先为每个列表分别生成大小为 2 的组合元组,然后计算这些组合列表的笛卡尔积:

import itertools
list1 = ["a", "b" , "c"]
list2 = ["d", "e"]

iter1 = itertools.combinations(list1, 2)
iter2 = itertools.combinations(list2, 2)

# If you want to add a subset of size 2 from list 2: 
product = itertools.product(iter1, iter2)
answer = list(map(lambda x: (*x[0], *x[1]), product))
# [('a', 'b', 'd', 'e'), ('a', 'c', 'd', 'e'), ('b', 'c', 'd', 'e')]

但是,如果您想添加 list2 的所有元素,您可以使用:

import itertools
list1 = ["a", "b" , "c"]
list2 = ["d", "e", "f"]

iter1 = itertools.combinations(list1, 2)

# If you want to add all elements of list2
product = itertools.product(iter1, [list2])
answer = list(map(lambda x: (*x[0], *x[1]), product))
# [('a', 'b', 'd', 'e', 'f'), ('a', 'c', 'd', 'e', 'f'), ('b', 'c', 'd', 'e', 'f')]