【问题标题】:Built in iteration counter for python [duplicate]内置python迭代计数器[重复]
【发布时间】:2015-06-09 10:37:04
【问题描述】:

我想遍历一个列表并引用我正在进行的迭代编号。我可以用一个简单的计数器来做到这一点,但是有内置函数吗?

List= list(range(0,6))
count = 0
for item in List:
    print "This is interation ", str(count)
    count += 1

【问题讨论】:

    标签: python python-2.7 iteration


    【解决方案1】:

    你应该使用内置函数enumerate

    【讨论】:

      【解决方案2】:

      这就是enumerate 的用途!

      enumerate(sequence, start=0)

      返回一个枚举对象。序列必须是序列、迭代器或>支持迭代的其他对象。

      >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
      >>> list(enumerate(seasons))
      [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
      

      在迭代中你可以这样做:

      for index,element in enumerate(seasons):
           #do stuff
      

      【讨论】:

        猜你喜欢
        • 2015-01-01
        • 1970-01-01
        • 2018-02-06
        • 1970-01-01
        • 2015-09-20
        • 2013-04-09
        • 1970-01-01
        • 1970-01-01
        • 2012-04-30
        相关资源
        最近更新 更多