[英]Split a list into all pairs in all possible ways
我知道有很多類似問題的帖子,並且已經遍歷了所有問題。 但是,我無能為力。
我有一個列表說l1=[0,1,2,3,4]
我想將其划分為一對元組,如下所示:
[(0, 1), (2, 3), 4],
[(0, 1), (2, 4), 3],
[(0, 1), (3, 4), 2],
[(0, 2), (1, 3), 4],
[(0, 2), (1, 4), 5],
[(0, 2), (3, 4), 1],
[(0, 3), (1, 2), 4],
[(0, 3), (2, 4), 1],
[(0, 3), (1, 4), 2],
[(0, 4), (1, 2), 3],
[(0, 4), (1, 3), 2],
[(0, 4), (2, 3), 1]
我嘗試了如何在所有可能的方式中將列表拆分成對的方法 。
def all_pairs(lst):
if len(lst) < 2:
yield lst
return
a = lst[0]
for i in range(1,len(lst)):
pair = (a,lst[i])
for rest in all_pairs(lst[1:i]+lst[i+1:]):
yield [pair] + rest
我得到以下輸出:
[(0, 1), (2, 3), 4]
[(0, 1), (2, 4), 3]
[(0, 2), (1, 3), 4]
[(0, 2), (1, 4), 3]
[(0, 3), (1, 2), 4]
[(0, 3), (1, 4), 2]
[(0, 4), (1, 2), 3]
[(0, 4), (1, 3), 2]
我發現我想要的列表中缺少一些組合。
我將不勝感激任何建議嗎?
您可以使用itertools.permutations
並使用frozenset
過濾出重復frozenset
:
In [173]: d = {frozenset([frozenset(x[:2]), frozenset(x[2:4]), x[-1]]) for x in itertools.permutations(l1,
...: len(l1))}
In [174]: d2 = [sorted(x, key=lambda x: (not isinstance(x, frozenset), x)) for x in d]
In [175]: sorted([[tuple(x[0]), tuple(x[1]), x[-1]] for x in d2])
Out[175]:
[[(0, 4), (2, 3), 1],
[(1, 2), (0, 3), 4],
[(1, 2), (0, 4), 3],
[(1, 2), (3, 4), 0],
[(1, 3), (0, 2), 4],
[(1, 3), (0, 4), 2],
[(1, 3), (2, 4), 0],
[(1, 4), (0, 2), 3],
[(1, 4), (0, 3), 2],
[(2, 3), (0, 1), 4],
[(2, 3), (1, 4), 0],
[(2, 4), (0, 1), 3],
[(2, 4), (0, 3), 1],
[(3, 4), (0, 1), 2],
[(3, 4), (0, 2), 1]]
您可以使用itertools.permutations
,然后使用列表推導從每個置換的前4個項目中創建對:
l1=[0,1,2,3,4]
from itertools import permutations
l2 = permutations(l1)
l3 = [[(x[0], x[1]), (x[2], x[3]), x[4]] for x in l2]
[[(0, i), tuple(item for item in l if item not in {0, i ,j}), j] for i in range(1, 5) for j in [item for item in l if item not in {0, i}]]
[[(0, 1), (3, 4), 2],
[(0, 1), (2, 4), 3],
[(0, 1), (2, 3), 4],
[(0, 2), (3, 4), 1],
[(0, 2), (1, 4), 3],
[(0, 2), (1, 3), 4],
[(0, 3), (2, 4), 1],
[(0, 3), (1, 4), 2],
[(0, 3), (1, 2), 4],
[(0, 4), (2, 3), 1],
[(0, 4), (1, 3), 2],
[(0, 4), (1, 2), 3]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.