【问题标题】:How do I find all indexes that have same string in a list?如何在列表中找到所有具有相同字符串的索引?
【发布时间】:2015-10-11 04:50:50
【问题描述】:
在Hangman游戏中,如果隐藏词是hello,玩家猜到l,那么我需要找到两个位置的索引。
例子:
word = "hello"
guess = "l"
position = word.index(guess) #this helps me find the first one
我想不出任何办法找到第二个。我怎么能做到这一点?
【问题讨论】:
标签:
python
list
python-3.x
indexing
【解决方案1】:
嗯,你可以使用enumerate 和列表理解:
>>> s = "hello"
>>> indexes = [i for i, v in enumerate(s) if v == "l"]
>>> indexes
[2, 3]
【解决方案2】:
专门针对刽子手:
>>> word = 'hello'
>>> guess = 'l'
>>> puzzle = ''.join(i if i == guess else '_' for i in word)
>>> print(puzzle)
__ll_
【解决方案3】:
您可以做的另一件事是预处理 单词并在映射中拥有已经可用的索引列表,这样您就不必一直遍历字符串,只需一次。
word = "hello"
map = {}
for i, c in enumerate(word):
if (c in map):
map[c].append(i)
else:
map[c] = [i]
然后,检查猜中的字母是否在 map 中。如果存在,则该字母存在,否则不存在。