排列后我有这个列表:
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/