[英]Find all combinations of tuples inside of a list
我試圖在長度為 2 的列表中找到元組內項目的所有排列。元組相互之間的順序無關緊要。
perm = [(3, 6), (6, 8), (4, 1), (7, 4), (5, 3),
(1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
(6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]
上述列表的一種排列的示例是:
perm = [(6, 3), (6, 8), (4, 1), (7, 4), (5, 3),
(1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
(6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]
另一個示例排列是:
perm = [(6, 3), (8, 6), (1, 4), (4, 7), (3, 5),
(9, 1), (5, 2), (8, 4), (1, 5), (7, 3),
(9, 6), (2, 10), (10, 7), (2, 8), (10, 9)]
最后,排列列表的長度應該是 32768,因為每個元組要么被交換,要么不被交換,並且 2^15 = 32768。我不關心元組相互之間的順序,只關心元組內部項目的排列。
我曾嘗試使用 itertools permute、combinations 和 product,但一直無法得到想要的結果。
您可以使用product
:
from itertools import product
lst = [(3, 6), (6, 8), (4, 1), (7, 4), (5, 3),
(1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
(6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]
output = product(*([(x, y), (y, x)] for x, y in lst))
output = list(output) # if you want a list, rather than a generator
print(len(output))
# 32768
print(output[0])
# ((3, 6), (6, 8), (4, 1), (7, 4), (5, 3), (1, 9), (2, 5), (4, 8), (5, 1), (3, 7), (6, 9), (10, 2), (7, 10), (8, 2), (9, 10))
print(output[-1])
# ((6, 3), (8, 6), (1, 4), (4, 7), (3, 5), (9, 1), (5, 2), (8, 4), (1, 5), (7, 3), (9, 6), (2, 10), (10, 7), (2, 8), (10, 9))
關鍵是寫類似
output = product([(3,6), (6,3)], [(6,8), (8,6)], ..., [(9,10), (10,9)])
以通用方式,以便任何輸入列表都可以工作,這是由生成器表達式和解包 ( *
) 完成的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.