【问题标题】:Get unique combinations of elements from a python list [duplicate]从python列表中获取元素的唯一组合[重复]
【发布时间】:2013-08-14 15:10:27
【问题描述】:

编辑: 这不是 How to get all possible combinations of a list’s elements? 的完全相同的副本

本主题是关于寻找唯一组合,而另一个主题是关于寻找所有组合。

如果我有一个 python 列表:

 L = [1,2,3,4]

从下面的列表中获取 3 个元素的所有可能的独特组合的最佳方法是什么:

["1,2,3", "1,2,4", "2,3,4", "3,4,1"]

组合中元素的顺序无关紧要。例如,"1,2,3""3,2,1" 将被视为相同的组合。

我可能可以编写几个循环来做到这一点,但我认为可能有一个单行可以做到这一点。

【问题讨论】:

    标签: python list combinations


    【解决方案1】:

    你需要itertools.combinations:

    >>> from itertools import combinations
    >>> L = [1, 2, 3, 4]
    >>> [",".join(map(str, comb)) for comb in combinations(L, 3)]
    ['1,2,3', '1,2,4', '1,3,4', '2,3,4']
    

    【讨论】:

    • 有趣的是,这确实为您提供了基于可迭代位置的唯一组合,而不是基于值,如文档中所述,请参见例如: from itertools import combination L = [1, 2, 3, 4, 4] [",".join(map(str, comb)) for comb in combination(L, 3)]
    猜你喜欢
    • 1970-01-01
    • 2020-04-30
    • 2022-08-19
    • 1970-01-01
    • 2021-06-02
    • 2012-10-05
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    相关资源
    最近更新 更多