![](/img/trans.png)
[英]How to return a list of all the indexes in the string that have capital letters?
[英]How do I find all indexes that have same string in a list?
在《 Hangman》游戲中,如果隱藏的單詞是“ hello
,而玩家猜到了l
那么我需要找到兩個位置的索引。
例:
word = "hello"
guess = "l"
position = word.index(guess) #this helps me find the first one
我找不到任何辦法找到第二個。 我該怎么做?
好吧,您可以使用enumerate
和列表理解:
>>> s = "hello"
>>> indexes = [i for i, v in enumerate(s) if v == "l"]
>>> indexes
[2, 3]
專為子手:
>>> word = 'hello'
>>> guess = 'l'
>>> puzzle = ''.join(i if i == guess else '_' for i in word)
>>> print(puzzle)
__ll_
您可以做的另一件事是對單詞進行預處理 ,並在映射中具有可用的索引列表,因此您不必一直遍歷字符串,只需一次。
word = "hello"
map = {}
for i, c in enumerate(word):
if (c in map):
map[c].append(i)
else:
map[c] = [i]
然后,檢查猜中的字母是否在地圖上 。 如果是,則該字母存在,否則不存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.