问题:获取Python FOR循环中的循环计数

for遍历列表的Python 循环中,我们可以编写:

for item in list:
    print item

整齐地遍历列表中的所有元素。有没有办法知道循环中到目前为止我循环了多少次?例如,我要列出一个列表,在处理完10个元素之后,我想对它们进行处理。

我想到的替代方案可能是这样的:

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)来获得到目前为止的迭代次数?

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?


回答 0

pythonic的方法是使用enumerate

for idx,item in enumerate(list):

The pythonic way is to use enumerate:

for idx,item in enumerate(list):

回答 1

同意尼克。这是更详细的代码。

#count=0
for idx, item in enumerate(list):
    print item
    #count +=1
    #if count % 10 == 0:
    if (idx+1) % 10 == 0:
        print 'did ten'

我已经在您的代码中注释掉了count变量。

Agree with Nick. Here is more elaborated code.

#count=0
for idx, item in enumerate(list):
    print item
    #count +=1
    #if count % 10 == 0:
    if (idx+1) % 10 == 0:
        print 'did ten'

I have commented out the count variable in your code.


回答 2

我知道一个比较老的问题,但是….发现其他东西,所以我投篮了:

[each*2 for each in [1,2,3,4,5] if each % 10 == 0])

I know rather old question but….came across looking other thing so I give my shot:

[each*2 for each in [1,2,3,4,5] if each % 10 == 0])

回答 3

使用zip函数,我们可以同时获取元素和索引。

countries = ['Pakistan','India','China','Russia','USA']

for index, element zip(range(0,countries),countries):

         print('Index : ',index)
         print(' Element : ', element,'\n')

output : Index : 0 Element : Pakistan ...

也可以看看 :

Python.org

Using zip function we can get both element and index.

countries = ['Pakistan','India','China','Russia','USA']

for index, element zip(range(0,countries),countries):

         print('Index : ',index)
         print(' Element : ', element,'\n')

output : Index : 0 Element : Pakistan ...

See also :

Python.org


回答 4

尝试使用 itertools.count([n])

Try using itertools.count([n])


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。