在Hang子手游戏中,如果隐藏的词是hello
,玩家猜测l
那么我需要找到两个位置的索引。如何查找列表中具有相同字符串的所有索引?
例子:
word = "hello"
guess = "l"
position = word.index(guess) #this helps me find the first one
我不能想出什么办法找到第二个。我怎么能做到这一点?
在Hang子手游戏中,如果隐藏的词是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]
谢谢你的帮助! – Mete
专门为刽子手:
>>> 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]
比,检查猜测信是地图。如果是这样,那封信就会存在,否则它不会。
也在这里回答http://stackoverflow.com/questions/11122291/python-find-char-in-string-can-i-get-all-indexes#11122355 – ziddarth