【问题标题】:splitting a sequence into pair combinations将序列拆分成对组合
【发布时间】:2017-06-27 14:24:15
【问题描述】:

抱歉,如果我没有很好地提出我的问题,我会尽力做到这一点:

如何获得一个列表以返回其中的每个可能的配对组合?

例如

a = [1,2,3,4]

我想知道如何获得这样的结果:

a= [ [1,2], [1,3] , [1,4], [2,3] , [2,4] , [3,4] ]

【问题讨论】:

标签: python list


【解决方案1】:

您可以在 itertools 模块中使用combinations

>>> import itertools as it
>>> it.combinations([1,2,3,4],2)
<itertools.combinations object at 0x106260fc8>
>>> list(it.combinations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

【讨论】:

  • 谢谢,我得看看整个 itertools 模块,看起来真的很有用
【解决方案2】:
>>> import itertools
>>> a = [1,2,3,4]
>>> list(itertools.combinations(a, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2015-07-26
    • 2015-01-08
    • 2012-01-19
    相关资源
    最近更新 更多