Get loop count inside a Python FOR loop

后端 未结 5 973
故里飘歌
故里飘歌 2020-11-28 00:42

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 t

相关标签:
5条回答
  • 2020-11-28 01:01

    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

    0 讨论(0)
  • 2020-11-28 01:09

    Try using itertools.count([n])

    0 讨论(0)
  • 2020-11-28 01:12

    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])
    
    0 讨论(0)
  • 2020-11-28 01:13

    The pythonic way is to use enumerate:

    for idx,item in enumerate(list):
    
    0 讨论(0)
  • 2020-11-28 01:20

    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.

    0 讨论(0)
提交回复
热议问题