[英]Finding index of the same elements in a list
Suppose I have to find each index of letter 'e' in the word "internet": 假设我必须在“互联网”一词中找到字母'e'的每个索引:
letter = 'e'
word = 'internet'
idx = word.index(letter)
But this code gives only the first index. 但是这段代码只给出了第一个索引。 How can I find the rest of them? 我怎样才能找到其余的?
Mark's answer is better for a single letter. 马克的答案对于一封信来说更好。 I'm adding this in case your real substring is longer than a single character. 我正在添加它,以防你的真实子串长于一个字符。
If you want to use str.index()
, it can take an optional start
position and will raise
a ValueError
if the desired substring is not found: 如果要使用str.index()
,它可以采用可选的start
位置,如果找不到所需的子字符串,则会raise
ValueError
:
>>> letter = 'e'
>>> word = 'internet'
>>> last_index = -1
>>> while True:
... try:
... last_index = word.index(letter, last_index + 1)
... print last_index
... except ValueError:
... break
...
3
6
Try this: 尝试这个:
word = 'internet'
letter = 'e'
[i for i in xrange(len(word)) if word[i] == letter]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.