在编码方面,我还是一个菜鸟,我正在尝试创建自己的子手游戏。在猜测单词中多次出现的字符时,我遇到了一些困难。

这是我的代码片段:

def random_word():
#word generator
randomized = random.randint(0,(len(content_words)-1))
word_to_guess = content_words[randomized].lower()
splitted = []
word_progress = []
for character in word_to_guess:
    splitted.append(character.lower())
    word_progress.append("?")
counter = 0
while counter <= 5:
    print(word_to_guess)
    print(splitted)
    print(word_progress)
    #Start of the game
    options = str(input("Do you want to guess the word or the characters?: ").lower())
    #word
    if options == "word":
        guess_word = input("Please your guess of the word: ").lower()
        if guess_word == word_to_guess:
            print("Correct! The word was " + word_to_guess + " you only needed " + str(counter) + " tries!")
            break
        elif guess_word != word_to_guess:
            counter += 3
            print("You have entered the wrong word ! You now have " + str(5-counter) + " tries left!")
            continue
            #characters
    elif options == "characters":
        guess_character = input("Please enter the character you would like to enter!: ")
        if guess_character in splitted and len(guess_character) ==  1:
            print("Correct! The character " + guess_character.upper() + " is in the word were looking for!" )
            for char in word_to_guess:
                if char == guess_character:
                    word_progress[word_to_guess.index(char)] = word_to_guess[word_to_guess.index(char)]
            continue


....因此,基本上在字符部分中,只有第一个出现的猜测字符才会实现到word_to_guess列表中。解决此问题的最佳方法是什么?

顺便说一句,这是我曾经问过的关于编码的第一个问题,在这个平台上,如果我没有真正以最有效的方式提出问题,请原谅。

最佳答案

index仅返回字符首次出现的索引。

您应该使用enumerate来同时遍历字符和索引:

for index, char in enumerate(word_to_guess):
    if char == guess_character:
        word_progress[index] = guess_character

关于python - 处理列表中多次出现的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58680688/

10-10 19:49