Python 替换列表中的字符

Python 替换列表中的字符,python,string,list,replace,Python,String,List,Replace,我正在做一个刽子手项目,我很难检查多个同一字母的单词,比如“大象” 我目前的做法是: enter_number = int(input("Please enter an integer number (0<=number<10) to choose the word in the list:")) chosen_word = words[enter_number] ini_guess = "_"*len(chosen_word) list_01 = list(ini_guess)

我正在做一个刽子手项目,我很难检查多个同一字母的单词,比如“大象”

我目前的做法是:

enter_number = int(input("Please enter an integer number (0<=number<10) to choose the word in the list:"))
chosen_word = words[enter_number]
ini_guess = "_"*len(chosen_word)
list_01 = list(ini_guess)

if letter_input in chosen_word:
    for letter in chosen_word:
        if letter == letter_input:
            list_01.pop(chosen_word.index(letter_input))
            list_01.insert(chosen_word.index(letter_input),letter_input)
            print("The letter is in the word")
                print("Letters matched so far:","".join(list_01))

enter_number=int(输入(“请输入整数(0我尽量避免
pop
insert
),列表理解更容易阅读:

此外,当你想一个字母一个字母地替换字符串时,字符串并不适合使用。最好是列出字符

matches = ['_' for _ in chosen_word]
我不知道为什么在您尝试实现hangman时让用户输入一个整数,您不想让他们猜字母吗?假设您从用户那里收到一封字母,并将其命名为
字母

mask = [x == letter for x in chosen_word]
现在您有了一个布尔值列表,如果字母在此位置匹配,则为True,否则为false。将匹配列表中的字母替换为:

for index, bool in enumerate(mask):
    if bool == True:
        matches[index] = letter

假设单词是“大象”,他们猜出“e”,然后加入(匹配)
将打印
'e_e_________.

您在中使用该
对整个列表进行一次迭代,然后使用该
再次进行迭代,每次调用
索引
都会再次进行迭代。这不仅浪费性能,而且过于复杂,更容易出错

事实上,几乎每次你认为你想要
list.index
,你实际上都不想要,因为你会遇到重复值的问题,而这正是你遇到的问题。如果你在
elephant
中要求
e
的索引,列表无法知道你是否想要
2
而不是
0
。知道这一点的唯一方法是在进行过程中跟踪索引,例如使用
enumerate
函数

因此,更好的解决方案是只循环一次:

for i, letter in enumerate(chosen_word):
    if letter == letter_input:
        list_01[i] = letter_input
        print("The letter is in the word")
        print("Letters matched so far:","".join(list_01))
一旦你把它简化成这样,你会注意到第二个问题:每次出现的时候,你都要打印“字母在单词中”一次,而不是一次,而且你还要打印“到目前为止匹配的字母”“它每次出现一次,如果根本不出现,就意味着根本不出现。但现在应该更清楚地知道如何解决这些问题

如果您了解列表理解和
zip
,进一步简化它可能会更清楚:

list_01 = [letter_input if letter_input == letter else oldval
           for oldval, letter in zip(list_01, chosen_word)]
使用enumerate()获取索引和索引处的字母

if letter_input in chosen_word:
    for i,letter in enumerate(chosen_word):
        if letter == letter_input:
            list_01[i] = letter_input
            print("The letter is in the word")
            print("Letters matched so far:","".join(list_01))

定义“遇到麻烦”。你的问题到底是什么?好吧,在一个刽子手游戏中,如果你猜到一个字母,你不需要填上字母出现的所有空格吗?如果发生多次,你不需要将字母映射到它的空格。