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

Ran*_*ang 14 python python-itertools

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)]
Run Code Online (Sandbox Code Playgroud)

但我想获得组合的指数,如:

index = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

fre*_*ini 18

你可以使用枚举:

>>> 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)]
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以使用 range 来获取生成的索引的顺序combinations

>>> list(itertools.combinations(range(3), 2))
[(0, 1), (0, 2), (1, 2)]
Run Code Online (Sandbox Code Playgroud)

所以你可以使用len(a)

>>> list(itertools.combinations(range(len(a)), 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
Run Code Online (Sandbox Code Playgroud)