Python列表组合

标签 python python-itertools

我有一个列表:

nums = [1, 2, 3, 4]

我想获得拆分列表 1 - 3 的所有可能性:

[
    ( 1, (2, 3, 4) ),
    ( 2, (1, 3, 4) ),
    ( 3, (1, 2, 4) ),
    ( 4, (1, 2 ,3) )
]

现在我能找到的最好的方法是使用 itertools.combinations(num, 3),但它只会给出每个项目的第二部分,即 [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]。我可以使用其他方法吗?

最佳答案

根据您要解决的问题的普遍性,解决方案可能或多或少简单:)

In [1]: nums = [1, 2, 3, 4]

In [2]: [(x, tuple(y for y in nums if y != x)) for x in nums]
Out[2]: [(1, (2, 3, 4)), (2, (1, 3, 4)), (3, (1, 2, 4)), (4, (1, 2, 3))]

如果列表中有重复值,使用索引进行比较:

In [3]: [(x, tuple(y for j, y in enumerate(nums) if j != i)) for i, x in enumerate(nums)]
Out[3]: [(1, (2, 3, 4)), (2, (1, 3, 4)), (3, (1, 2, 4)), (4, (1, 2, 3))]

关于Python列表组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531645/

相关文章:

python - Node.js 是否有相当于 Python 迭代器工具?

python - 使用 Pandas 聚合所有数据框行对组合

python - 内存错误 : numpy. genfromtxt()

python - 使用 matplotlib 散点图函数指向错误的 z 坐标

python - 将两个数组聚合成具有给定形状的单个数组的正确方法

python - itertools 产品使用太多内存

python - 给出字典的笛卡尔积

python - 如何获取 csv 文件的子集作为 Spark RDD

python - 在 venv 中使用 python2.7,其中 python3 是默认 python

Python - 有效地从两个字典中获取所有可能的组合