Python For loop get index

This question already has an answer here:

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

  • 使用enumerate()函数生成索引以及要循环的序列元素:

    for index, w in enumerate(loopme):
        print "CURRENT WORD IS", w, "AT CHARACTER", index 
    

    Do you want to iterate over characters or words?

    For words, you'll have to split the words first, such as

    for index, word in enumerate(loopme.split(" ")):
        print "CURRENT WORD IS", word, "AT INDEX", index
    

    This prints the index of the word.

    For the absolute character position you'd need something like

    chars = 0
    for index, word in enumerate(loopme.split(" ")):
        print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
        chars += len(word) + 1
    
    链接地址: http://www.djcxy.com/p/24000.html

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

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