以所有可能的方式将列表拆分为所有对 [英] Split a list into all pairs in all possible ways
本文介绍了以所有可能的方式将列表拆分为所有对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道很多帖子都有类似的问题,并且我都看过.但是,我无法做我需要的事情.
I am aware of many posts with the similar questions and have been through all of them. However, I am not able to do what I need.
我有列表说 l1=[0,1,2,3,4]
我想将其划分为如下的元组对:
I have list say l1=[0,1,2,3,4]
which I want to partition into pair of tuples like following:
[(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]
我发现我想要的列表中缺少一些组合.
I find that there are some combinations which are missing from the list which I want.
我会很感激任何建议吗?
I would appreciate any suggestion?
推荐答案
您可以使用 itertools.permutations
并使用 frozenset
过滤掉重复项:
You can use itertools.permutations
and filter out duplicates using 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]]
这篇关于以所有可能的方式将列表拆分为所有对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文