Python中的迭代计数?


问题内容

假设我有一个元组l的列表,并且我做这样的事情:

for (a,b) in l:
     do something with a,b, and the index of (a,b) in l

有没有一种简单的方法来获取(a,b)的索引?我可以使用列表的索引方法,但是如果(a,b)不是唯一的怎么办?我也可以首先迭代索引,但是它很麻烦。有没有更简单的东西?


问题答案:

使用枚举

for i, (a, b) in enumerate(l):
    # i will be the index of (a, b) in l