Python For 循环获取索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15684605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:42:02  来源:igfitidea点击:

Python For loop get index

pythonloopsfor-loopindexing

提问by user1817081

I am writing a simple Python for loop to prnt the current character in a string. However, I could not get the index of the character. Here is what I have, does anyone know a good way to get the current index of the character in the loop?

我正在编写一个简单的 Python for 循环来打印字符串中的当前字符。但是,我无法获得角色的索引。这是我所拥有的,有没有人知道获取循环中角色当前索引的好方法?

 loopme = 'THIS IS A VERY LONG STRING WITH MANY MANY WORDS!'

 for w  in loopme:
    print "CURRENT WORD IS " + w + " AT CHARACTER " 

采纳答案by Martijn Pieters

Use the enumerate()functionto generate the index along with the elements of the sequence you are looping over:

使用该enumerate()函数生成索引以及您正在循环的序列元素:

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

回答by glglgl

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