【问题标题】:How to get single unique permutation entry from list如何从列表中获取单个唯一排列条目
【发布时间】:2016-11-17 07:40:40
【问题描述】:

我有这个排列后的列表:

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 python-2.7 list combinations permutation


    【解决方案1】:

    您需要列表的组合,而不是排列。为此,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

    • 排列用于列表(顺序很重要)

    • 组合用于组(顺序无关紧要)

    【讨论】:

      猜你喜欢
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2011-10-19
      • 1970-01-01
      • 2016-08-24
      • 2019-05-09
      • 1970-01-01
      相关资源
      最近更新 更多