Python itertools.combinations:如何获取组合数字的索引 [英] Python itertools.combinations: how to obtain the indices of the combined numbers

查看:77
本文介绍了Python itertools.combinations:如何获取组合数字的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的itertools.combinations()创建的结果是数字的组合.例如:

The result created by Python's itertools.combinations() is the combinations of numbers. For example:

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

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

但是我也想获得组合的索引,例如:

But I would like to also obtain the indices of the combinations such as:

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:如何获取组合数字的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆