首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的代码不替换aardvark和狒狒例子中的重复字母?

为什么我的代码不替换aardvark和狒狒例子中的重复字母?
EN

Stack Overflow用户
提问于 2021-12-27 21:50:18
回答 1查看 118关注 0票数 0

为什么我的代码不替换食蚁兽和狒狒的重复字母?这是绞刑游戏的练习!

代码语言:javascript
复制
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`
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-27 22:04:58

chosen_word.index(letter)给出了letter的唯一第一次出现,所以您要一次又一次地在同一个位置替换一个字母。

一个直接的补救方法可能是使用index的第二个参数,该参数设置搜索的起始位置:

代码语言:javascript
复制
current = 0
for letter in chosen_word:
    if letter == guess:
           index = chosen_word.index(letter, current)
           display[index] = letter
           current = index + 1

一个更好的方法是使用enumerate直接获得每次迭代时所考虑的字母的位置。

代码语言:javascript
复制
for index, letter in enumerate(chosen_word):
    if letter == guess:
           display[index] = letter

另一种选择是使用列表理解和zip

代码语言:javascript
复制
display = [y if y == guess else x for x, y in zip(display, chosen_word)]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70500784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档