在 Python FOR 循环中获取循环计数 [英] Get loop count inside a Python FOR loop

查看:69
本文介绍了在 Python FOR 循环中获取循环计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在迭代列表的 Python for 循环中,我们可以编写:

In a Python for loop that iterates over a list we can write:

for item in list:
    print item

它整齐地遍历列表中的所有元素.有没有办法在循环内知道到目前为止我已经循环了多少次?例如,我想获取一个列表,在处理了 10 个元素后,我想对它们做一些事情.

and it neatly goes through all the elements in the list. Is there a way to know within the loop how many times I've been looping so far? For instance, I want to take a list and after I've processed ten elements I want to do something with them.

我想到的替代方案如下:

The alternatives I thought about would be something like:

count=0
for item in list:
    print item
    count +=1
    if count % 10 == 0:
        print 'did ten'

或者:

for count in range(0,len(list)):
    print list[count]
    if count % 10 == 0:
        print 'did ten'

有没有更好的方法(就像for item in list)来获得到目前为止的迭代次数?

Is there a better way (just like the for item in list) to get the number of iterations so far?

推荐答案

pythonic 的方式是使用 枚举:

The pythonic way is to use enumerate:

for idx,item in enumerate(list):

这篇关于在 Python FOR 循环中获取循环计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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