2 回答

TA貢獻1801條經驗 獲得超8個贊
以下操作即可:
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)]
這使得兩個列表中的相應組合的笛卡爾積,并簡單地連接每對以避免嵌套元組。

TA貢獻2065條經驗 獲得超14個贊
你需要先構建每個列表需要的組合,然后做產品,你還需要加入產品的內部結果((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
添加回答
舉報