python中最快的方法来枚举所有组合并返回索引

时间:2016-06-26 17:00:44

标签: python combinations

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

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

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

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

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

2 个答案:

答案 0 :(得分:1)

使用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))

答案 1 :(得分: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)]