Count indexes using “for” in Python

后端 未结 7 1306
清歌不尽
清歌不尽 2021-02-01 01:44

I need to do in Python the same as:

for (i = 0; i < 5; i++) {cout << i;} 

but I don\'t know how to use FOR in Python to get the index

相关标签:
7条回答
  • 2021-02-01 01:56

    If you have some given list, and want to iterate over its items and indices, you can use enumerate():

    for index, item in enumerate(my_list):
        print index, item
    

    If you only need the indices, you can use range():

    for i in range(len(my_list)):
        print i
    
    0 讨论(0)
  • 2021-02-01 01:58

    This?

    for i in range(0,5): 
     print(i)
    
    0 讨论(0)
  • 2021-02-01 02:01

    If you have an existing list and you want to loop over it and keep track of the indices you can use the enumerate function. For example

    l = ["apple", "pear", "banana"]
    for i, fruit in enumerate(l):
       print "index", i, "is", fruit
    
    0 讨论(0)
  • 2021-02-01 02:01

    use enumerate:

    >>> l = ['a', 'b', 'c', 'd']
    >>> for index, val in enumerate(l):
    ...    print "%d: %s" % (index, val)
    ... 
    0: a
    1: b
    2: c
    3: d
    
    0 讨论(0)
  • 2021-02-01 02:11

    The most simple way I would be going for is;

    i = -1
    for step in my_list:
        i += 1
        print(i)
    
    #OR - WE CAN CHANGE THE ORDER OF EXECUTION - SEEMS MORE REASONABLE
    
    i = 0
    for step in my_list:
        print(i) #DO SOMETHING THEN INCREASE "i"
        i += 1
    
    0 讨论(0)
  • 2021-02-01 02:13

    In additon to other answers - very often, you do not have to iterate using the index but you can simply use a for-each expression:

    my_list = ['a', 'b', 'c']
    for item in my_list:
        print item
    
    0 讨论(0)
提交回复
热议问题