gpt4 book ai didi

Python itertools.combinations : how to obtain the indices of the combined numbers

转载 作者:太空狗 更新时间:2023-10-29 17:17:14 31 4
gpt4 key购买 nike

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

我该怎么做?

最佳答案

你可以使用枚举:

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

关于Python itertools.combinations : how to obtain the indices of the combined numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27150990/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com