Skip to main content
 首页 » 编程设计

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

2025年05月04日24lovecherry

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

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