How to get list index and element simultaneously in Python?

This question already has an answer here:

  • Accessing the index in 'for' loops? 17 answers

  • You can use enumerate :

    for k,i in enumerate(mylist):
        #do something with index k
        #do something with element i
    

    More information about looping techniques.

    Edit:
    As pointed out in the comments, using other variable names like

    for i, item in enumerate(mylist):
    

    makes it easier to read and understand your code in the long run. Normally you should use i , j , k for numbers and meaningful variable names to describe elements of a list.
    Ie if you have eg a list of books and iterate over it, then you should name the variable book .


    enumerate是答案:

    for index, element in enumerate(iterable):
        #work with index and element
    
    链接地址: http://www.djcxy.com/p/24002.html

    上一篇: 如何在python中迭代数组时输出索引

    下一篇: 如何在Python中同时获取列表索引和元素?