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

标签 python list partitioning

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

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

相关文章:

Python:如何在嵌套循环的第一列中搜索?

postgresql - 如何交叉引用其他表的数据进行分区检查?

python - 将 Ply 与 iPython/Jupyter 结合使用

python - Python 和 Selenium : authenticate against Active Directory 的解决方法

python - 使用 pd.merge 使用引用表填充左侧数据帧上的缺失值

python - 关于 gunicorn worker 的最佳数量

swift - 无法使 Realm List<T> 符合 NSCopying

c# - 按日期对数组项进行分组

scala - 如何在 Spark 中使用 RangePartitioner

sql - 范围分区跳过检查