[英]How do I find all indexes that have same string in a list?
In a game of Hangman, if the hidden word is hello
and the player guesses l
then I need to find the index of both locations. 在《 Hangman》游戏中,如果隐藏的单词是“ hello
,而玩家猜到了l
那么我需要找到两个位置的索引。
Example: 例:
word = "hello"
guess = "l"
position = word.index(guess) #this helps me find the first one
I couldn't come up with any way to find the second. 我找不到任何办法找到第二个。 How am I able to do that? 我该怎么做?
Well, you could use enumerate
and a list comprehension: 好吧,您可以使用enumerate
和列表理解:
>>> s = "hello"
>>> indexes = [i for i, v in enumerate(s) if v == "l"]
>>> indexes
[2, 3]
Specifically for hangman: 专为子手:
>>> word = 'hello'
>>> guess = 'l'
>>> puzzle = ''.join(i if i == guess else '_' for i in word)
>>> print(puzzle)
__ll_
Another thing you could do, is preprocess the word and have the list of indexes already available in a map so you do not have to iterate trough the string all the time, only once. 您可以做的另一件事是对单词进行预处理 ,并在映射中具有可用的索引列表,因此您不必一直遍历字符串,只需一次。
word = "hello"
map = {}
for i, c in enumerate(word):
if (c in map):
map[c].append(i)
else:
map[c] = [i]
Than, check that the letter guessed is in map . 然后,检查猜中的字母是否在地图上 。 If it is, the letter exists otherwise it does not. 如果是,则该字母存在,否则不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.