我知道很多帖子都有类似的问题并且已经通过了所有这些问题。但是,我无法做我需要的事。
我有一个列表说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]
我尝试了帖子how-to-split-a-list-into-pairs-in-all-possible-ways中的解决方案。
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]
我发现列表中缺少一些我想要的组合。
我很感激任何建议吗?
答案 0 :(得分:3)
您可以使用itertools.permutations
并使用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]]
答案 1 :(得分: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]
答案 2 :(得分:1)
[[(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]]