所以我刚刚开始学习 python,并且正在为一个项目创建一个刽子手游戏。我被卡住了。让我给你一些背景知识。
我让程序去除字母表中的字母,并将它们添加到被猜单词的空格处,但它只会找到第一个字母的索引。因此,可以说我试图猜测的词是故障安全的。现在假设我猜字母 f。它返回 f _ _ _ _ _ _ _ 而不是 f _ _ _ _ _ f _。在我看来,一旦 for 循环在列表中找到字母的第一个实例并在那里中断,它就会停止。我需要找到并显示字母的所有实例。
代码:
def makechoice(list)
# defines the word trying to be guessed as a list of letters
Global listword
#defines the amount of blanks in listword as a list "_ "
global blanks
#user input to guess a letter
current = raw_input("Please enter your guess:")
for a in listword:
if a == current:
t = listword.index(a)
#puts the letter and a blank in place of the unoccupied space if it is a match.
blanks[t] = str(listword[t]) + " "
不,这是我的问题,还是不应该循环遍历 listword 中的所有字母,如果找到 2 个“f”,则将它们都显示出来。请有人帮忙。我已经进行了研究,但似乎无法弄清楚我遗漏了什么。
最佳答案
.index()
返回给定字符的第一个索引。如果单词多次具有相同的字符,它将只返回第一个索引(除非您明确指定起始偏移量)。
当您需要在迭代期间访问索引时,您应该使用 enumerate()
.
for i, x in enumerate(listword):
# i is the index, x is the character
if x == current:
blanks[i] = listword[i] + " "
关于Python,在字母列表中找到多个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20039022/