【问题标题】:Iteration count in python?python中的迭代次数?
【发布时间】:2011-12-21 13:48:45
【问题描述】:

假设我有一个元组列表 l,我会这样做:

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

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

【问题讨论】:

    标签: python


    【解决方案1】:

    使用enumerate

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

    【讨论】:

      【解决方案2】:

      使用enumerate():

      for i,(a,b) in enumerate(l):
         ... # `i` contains the index
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-16
        • 1970-01-01
        • 2021-10-05
        • 1970-01-01
        • 2013-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多