简体   繁体   English

如何找到列表中具有相同字符串的所有索引?

[英]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.

相关问题 如何返回字符串中具有大写字母的所有索引的列表? - How to return a list of all the indexes in the string that have capital letters? 如何在python中相同的元组列表中找到所有元素? - How do i find all the elements in a list of tuples that are same in python? 如何将列表中的所有整数乘以它们的索引相加? - How do I sum all integers in a list multiplied by their indexes? 如何在Python中查找列表中所有为空的索引 - How to find all indexes of a list that are empty in Python 如何在字符串中查找字符并获取所有索引? - How to find char in string and get all the indexes? function 应该返回字符串中所有具有大写字母的索引的列表 - function should return a list of all the indexes in the string that have capital letters 如何在父字符串列表中查找与子字符串列表对应的索引 - How to find in a parent string list, the indexes corresponding to a child string list 我有一个数字的素因子的Python列表。 我如何(pythonically)找到所有因素? - I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors? 给定索引列表,如何在这些索引上拆分DataFrame? - Given a list of indexes, how do I split a DataFrame on those indexes? 如何在列表列表中获取相同值的所有出现的索引列表? - How to get list of indexes of all occurences of the same value in list of lists?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM