为什么我的代码不替换食蚁兽和狒狒的重复字母?这是绞刑游戏的练习!
import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
#Testing code
print(f'Pssst, the solution is {chosen_word}.')
display = []
for letter in chosen_word:
display.append("_")
print(display)
#TODO-1: - Create an empty List called display.
#For each letter in the chosen_word, add a "_" to 'display'.
#So if the chosen_word was "apple", display should be ["_", "_", "_", "_", "_"] with 5 "_" representing each letter to guess.
guess = input("Guess a letter: ").lower()
#TODO-2: - Loop through each position in the chosen_word;
#If the letter at that position matches 'guess' then reveal that letter in the display at that position.
#e.g. If the user guessed "p" and the chosen word was "apple", then display should be ["_", "p", "p", "_", "_"].
for letter in chosen_word:
if letter == guess:
index = chosen_word.index(letter)
display[index] = letter
print(display)
#TODO-3: - Print 'display' and you should see the guessed letter in the correct position and every other letter replaced with "_".
#Hint - Don't worry about getting the user to guess the next letter. We'll tackle that in step 3.`enter code here`发布于 2021-12-27 22:04:58
chosen_word.index(letter)给出了letter的唯一第一次出现,所以您要一次又一次地在同一个位置替换一个字母。
一个直接的补救方法可能是使用index的第二个参数,该参数设置搜索的起始位置:
current = 0
for letter in chosen_word:
if letter == guess:
index = chosen_word.index(letter, current)
display[index] = letter
current = index + 1一个更好的方法是使用enumerate直接获得每次迭代时所考虑的字母的位置。
for index, letter in enumerate(chosen_word):
if letter == guess:
display[index] = letter另一种选择是使用列表理解和zip
display = [y if y == guess else x for x, y in zip(display, chosen_word)]https://stackoverflow.com/questions/70500784
复制相似问题