[英]Find indexes for a certain character in string
我是Python的完整入門者,我試圖為該字符串中的每個“ o”查找索引。 這僅顯示第一個o的索引,而我正在嘗試查找所有它們:
besedilo = "Dober dan Slovenija"
print (besedilo.index("o"))
我以為可以使用for循環,但是我不太確定該怎么做
使用enumerate()
:
>>> besedilo = "Dober dan Slovenija"
>>> [i for i, j in enumerate(besedilo) if j == 'o']
[1, 12]
這將遍歷字符串和從0開始的某種計數器。如果一個字母與'o'
匹配,則該計數將在列表推導返回的列表中。
另外,您可以使用itertools
模塊:
>>> import itertools
>>> [i for i, j in itertools.izip(itertools.count(), besedilo) if j == 'o'] # itertools.izip not needed if you are using Python 3
[1, 12]
請記住, enumerate()
效率更高:)。
對enumerate()
使用列表enumerate()
:
indices = [i for i, c in enumerate(besedilo) if c == 'o']
演示:
>>> besedilo = "Dober dan Slovenija"
>>> [i for i, c in enumerate(besedilo) if c == 'o']
[1, 12]
str.index()
方法還帶有一個可選的start
參數,即從中搜索的起始索引(默認為0),因此您可以使用最后一個位置+ 1構建一個循環以收集所有索引:
indices = []
next = -1
while True:
try:
next = besedilo.index(next + 1)
indices.append(next)
except ValueError:
break
如果速度是一個問題,那么最后一個方法實際上是兩者中較快的一種:
$ bin/python -m timeit -s "test = 'Dober dan Slovenija'" "indices = [i for i, c in enumerate(test) if c=='o']"
100000 loops, best of 3: 2.51 usec per loop
$ bin/python -m timeit -s "test = 'Dober dan Slovenija'" -s "indices,next=[],-1" "while True:" " try:" " next= test.index('o', next+1)" " indices.append(next)" " except ValueError: break"
1000000 loops, best of 3: 1.06 usec per loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.