Python itertools.combinations:如何获取组合数字的索引

27

Python 的 itertools.combinations() 函数生成的结果是数字的组合。例如:

a = [7, 5, 5, 4]
b = list(itertools.combinations(a, 2))

# b = [(7, 5), (7, 5), (7, 4), (5, 5), (5, 4), (5, 4)]

但我也想获得如下组合的索引:

index = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

我该怎么做?


9
itertools.combinations(range(len(a)), 2) 是什么意思? - jonrsharpe
3个回答

29

你可以使用enumerate:

>>> a = [7, 5, 5, 4]
>>> list(itertools.combinations(enumerate(a), 2))
[((0, 7), (1, 5)), ((0, 7), (2, 5)), ((0, 7), (3, 4)), ((1, 5), (2, 5)), ((1, 5), (3, 4)), ((2, 5), (3, 4))]
>>> b = list((i,j) for ((i,_),(j,_)) in itertools.combinations(enumerate(a), 2))
>>> b
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

6
您可以使用range函数获取组合函数(combinations)生成的索引顺序。
>>> list(itertools.combinations(range(3), 2))
[(0, 1), (0, 2), (1, 2)]

因此,您可以使用len(a)

>>> list(itertools.combinations(range(len(a)), 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

0
a = [7, 5, 5, 4]
n_combinations = 2

np.array(list(itertools.combinations(enumerate(a), n_combinations)))[...,0]

更具可扩展性的解决方案。与@fredtantini的示例不同,更改n_combinations不需要更改代码。它基本上是使用numpy切片表达的解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接