我是 Python 的新手,目前正在尝试编写我的第一段合适的代码,以模拟刽子手游戏。有一个问题我无法理解。我的代码如下所示:
import random
word_lst = ["green","red","blue"]
selected_word = random.choice(word_lst)
blank_lst = []
for element in range(len(selected_word)):
blank_lst.append("_")
choices_left = 10
selected_word_lst = list(selected_word)
while blank_lst != selected_word_lst and choices_left != 0:
print(blank_lst)
print(choices_left)
letter_selection = input("Choose a letter ")
if letter_selection in selected_word_lst:
print("correct selection")
for element in selected_word_lst:
letter_selection_pos = selected_word_lst.index(letter_selection)
blank_lst[letter_selection_pos] = letter_selection
else:
print("incorrect selection")
choices_left -= 1
if blank_lst == selected_word_lst:
print("You win")
elif choices_left == 0:
print("You lose")
明显的问题是,对于具有重复字母的单词(在我的小测试代码中为绿色),即使您正确选择了字母,程序也只会用正确选择的字母替换其中一个空格。
任何关于如何让它工作的提示都将不胜感激。
最佳答案
使用enumerate
遍历selected_word_list
中的字母;那么您就不必使用 index
来查找它们的位置。
https://stackoverflow.com/questions/67503274/