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

How to get single unique permutation entry from list

排列后我有这个列表:

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)]

提前致谢

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

>>> 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).