gpt4 book ai didi

python - 以所有可能的方式将列表拆分为所有对

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:50 25 4
gpt4 key购买 nike

我知道有很多帖子有类似的问题,并且已经看完了所有这些帖子。但是,我无法执行所需的操作。

我有列表说 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]

我发现我想要的列表中缺少一些组合。

我会很感激任何建议?

最佳答案

您可以使用 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]]

关于python - 以所有可能的方式将列表拆分为所有对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45704859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com