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

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

问题描述

 <$  for循环遍历一个列表, c $ c>列表中的项目:
打印项目

它整齐地贯穿所有列表中的元素。有没有办法知道在循环内有多少次我一直循环到目前为止?例如,我想列出一个列表,在处理了十个元素之后,我想和他们做一些事情。



我想过的方法是:

  count = 0 
列表中的项目:
列印项目
count + = 1
if count%10 == 0:
print'did ten'

或者:

 (0,len(列表)):
print list [count]
if count%10 == 0:
print'did ten'

一个更好的方法(就像列表中的)来获得迭代次数?

解决方案

pythonic方法是使用 enumerate

 对于idx,枚举(列表)中的项目:


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

for item in list:
    print item

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'

Or:

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

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

解决方案

The pythonic way is to use enumerate:

for idx,item in enumerate(list):

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

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