Loop through list with both content and index

This question already has an answer here:

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

  • 使用enumerate内置函数:http://docs.python.org/library/functions.html#enumerate


    使用enumerate()

    >>> S = [1,30,20,30,2]
    >>> for index, elem in enumerate(S):
            print(index, elem)
    
    (0, 1)
    (1, 30)
    (2, 20)
    (3, 30)
    (4, 2)
    

    Like everyone else:

    for i, val in enumerate(data):
        print i, val
    

    but also

    for i, val in enumerate(data, 1):
        print i, val
    

    In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don't want your index to start with the default value of zero.

    I was printing out lines in a file the other day and specified the starting value as 1 for enumerate() , which made more sense than 0 when displaying information about a specific line to the user.

    链接地址: http://www.djcxy.com/p/23998.html

    上一篇: Python for循环获取索引

    下一篇: 循环播放内容和索引列表