python - 如何从列表中获取单个唯一排列条目

标签 python python-2.7 list combinations permutation

排列后我有这个列表:

import itertools
print list(itertools.permutations([1,2,3,4], 2))

这是输出:

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

在该列表中,我们可以找到重复的元素,例如 (1,2) - (2,1) 和 (1,3) - (3,1) 等等 ..

我想要的是从此列表中只获取一个复制元素,输出列表如下:

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

提前致谢

最佳答案

您需要列表的组合,而不是排列。为此有 itertools.combinations() Python 中的函数:

>>> from itertools import combinations
>>> l = [1,2,3,4]
>>> list(combinations(l, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

根据 document :

  • Permutations are for lists (order matters)

  • Combinations are for groups (order doesn’t matter).

关于python - 如何从列表中获取单个唯一排列条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40649178/

相关文章:

python - simplejson 返回值不按顺序

python - 将排名添加到 ID 的数据框中

python-2.7 - 非位置但需要 argparse 参数

python - 检查列表中的所有值是否大于某个数字

python - 将列表分成对角线?

python - 清除 numpy 数组的元素

python - 评估 python 中的 for 循环,包含带有嵌入 for 循环的数组

python - 强制工作人员在启用持久交付模式时立即获取失败的消息

python - 如何在python中将项目放在队列的顶部?

Android:为自定义 ListAdapter 注册 ContextMenu