【问题标题】:fastest way in python to enumerate all combinations and return the indexpython中枚举所有组合并返回索引的最快方法
【发布时间】:2016-06-26 17:00:44
【问题描述】:

很难在标题中描述我的问题。我认为这个问题的标题不是很好。我的问题如下

假设我有一个列表 [0,0,0,0,0],我想将 3 个放入列表中的这 5 个插槽中。我想列举所有可能的组合。这种情况下是5选3,也就是10,例如,

[1,1,1,0,0]
[1,0,1,0,1]
....

我希望最终得到一个列表列表,使得大列表中的每个元素(仍然是一个列表)存储每个场景中这些元素的索引,例如,在上面的示例中,第一个元素最终的大列表应该是[0,1,2],最终大列表中的第二个元素应该是[0,2,4]...

有没有一种快速的方法来实现这一点?我想我需要使用库 itertools,但不确定我应该使用哪个特定功能

【问题讨论】:

    标签: python combinations


    【解决方案1】:

    这是你要找的吗?

    from itertools import combinations    
    num_ones = 3
    slots = 5
    comb_indices = list(combinations(range(5),3))
    print comb_indices
    

    [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

    【讨论】:

      【解决方案2】:

      使用itertools.combinations

      获取长度为 5 和 3 个的所有可能的二进制列表

      N = 5
      zeros = [0]*N
      for comb in itertools.combinations(range(N), r = 3):
          l = zeros.copy()
          for indice in comb:
              l[indice] = 1
      

      效率不是很高,但应该足够快。

      要获取索引的“大列表”,请使用itertools.combinations(range(5), 3))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-23
        相关资源
        最近更新 更多