python - 如何替换 list python 3 中的元素

我有一个 list (显示),我需要在用户输入时更新它。所以,如果用户输入字母 A,我需要用字母 A 来替换新 list 中的一个元素,称为 display。我可能没有正确编写此代码,但我被困在下面的代码中。我不确定如何编写代码来替换 list 中的元素 display.任何帮助或指导将不胜感激。 TIA

import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)

display = []
guess = input("Guess a letter: ").lower()

for numChar in range(len(chosen_word)):
    display += "_"

for letter in chosen_word:
    if letter == guess:

预期输出:

如果用户输入是“a”并且 selected_word 是 babs,因为它有一个“a”,我需要它用相应的字母替换 list ('', '', '', '') . ('', '一个', '', '_')

回答1

你想制造刽子手,不是吗?尝试这个:

import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)

display = []
guess = input("Guess a letter: ").lower()

if guess == chosen_word:
    display = list(chosen_word)
else
    for numChar in range(len(chosen_word)):
        if numChar == guess[0]:
            display.append(numChar)
        else
            display.append("_")

回答2

import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)

display = []
guess = input("Guess a letter: ").lower()

display[:] = [guess if x == guess else "_" for x in chosen_word]

回答3

使用 enumerate 获取每个字母及其索引:

import random

name_list = ["daniel", "babs", "cal"]
chosen_word = list(random.choice(name_list))
display = ["_" for _ in chosen_word]

while display != chosen_word:
    print(display)
    guess = input("Guess a letter: ").lower()
    for i, letter in enumerate(chosen_word):
        if letter == guess:
            display[i] = letter

相似文章