Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 附加到列表时,当前值将被覆盖_Python_List_Append - Fatal编程技术网

Python 附加到列表时,当前值将被覆盖

Python 附加到列表时,当前值将被覆盖,python,list,append,Python,List,Append,我是python的新手,您可能很容易帮助我。所以我有一个“猜测”列表,我想把“猜测”添加到列表中(顺便说一下,这是一个刽子手游戏),所以它可以很好地用于进入刽子手,但在下一个回合中,不是在列表中添加另一个猜测,而是更改了猜测 guessed = [] guessed.extend(guess) print (guessed) 这是我的更多代码,您可能需要: while current != theword and lives > 0: print ("You have %d lives

我是python的新手,您可能很容易帮助我。所以我有一个“猜测”列表,我想把“猜测”添加到列表中(顺便说一下,这是一个刽子手游戏),所以它可以很好地用于进入刽子手,但在下一个回合中,不是在列表中添加另一个猜测,而是更改了猜测

guessed = []
guessed.extend(guess)
print (guessed)
这是我的更多代码,您可能需要:

while current != theword and lives > 0:

print ("You have %d lives left" % lives)
guess = input("Please input one letter or type 'exit' to quit.")
guess = guess.lower()


if guess == "exit":
    break


guessed = []
guessed.append(guess)
print (guessed)


if guess in theword:
    index = theword.find(guess)
    x = list(current)
    x[index] = guess
    current = "".join(x)
    print ("Correct!")
    print(x)
    print (guessed)
else:
    print ("Incorrect, try again")
所以如果我第一次猜“m”,它会输出“[m]”,但是如果我猜“a”,它会输出“[a]”,而不是“[m,a]”。我想我必须做一些循环的事情,但我想不出来


谢谢

我想你的缩进是错误的,因为这里的格式

while
循环中,每次执行
猜测=[]
。此命令意味着“创建一个新列表并将其分配给名称
guessed
”,这将有效地用以前的猜测覆盖列表

在循环之前执行一次

您在开始时还使用了
extend
,但在主代码中使用了
append
。虽然在本例中没有问题,但您可能希望仔细阅读差异:并在大多数情况下坚持使用
append

此外,在更改元素之前,您不需要从字符串
current
中创建列表。这也很好:

current[index] = guess

这就是它应该是多么的珍贵

current = 's'
theword = 'm'
lives =3
guessed = []
while current != theword and lives > 0:
    print ("You have %d lives left" % lives)
    guess = raw_input("Please input one letter or type 'exit' to quit.\n>>")
    guess = guess.lower()


    if guess == "exit":
        break


    guessed.append(guess)
    print ("You guessed: %s" % " ".join(guessed))


    if guess in theword:
        index = theword.find(guess)
        x = list(current)
        x[index] = guess
        current = "".join(x)
        print ("Correct its '%s'\nYour guesses: %s" % (x, guessed))
    else:
        print ("Incorrect, try again")

请检查并更正缩进,它是这样错误的。请修复缩进。当您循环某个内容时,需要保持一个运行总数或向列表中添加某个内容时,您必须确保要更改的变量/列表在循环之外声明。另一方面,您将继续重新初始化到您开始使用的任何值。对于Python3.x,必须将
raw\u输入更改为
input