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

问题描述 投票:17回答:2

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)]

我该怎么办?

python itertools
2个回答
19
投票

您可以使用枚举:

>>> 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)]

1
投票

您可以使用范围来获取combinations产生的索引的顺序。

>>> list(combinations(range(3), 2))
[(0, 1), (0, 2), (1, 2)]

所以您可以使用len(a)

>>> list(combinations(range(len(a)), 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
© www.soinside.com 2019 - 2024. All rights reserved.