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

时间:2014-01-04 15:48:45

标签: python list append

我是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]”。我想我必须做一些循环,但我无法弄清楚这一点。

由于

2 个答案:

答案 0 :(得分:1)

我认为你的缩进只是错误,因为这里有格式化。

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

在循环之前执行一次。

您也可以在开头使用extend,但在主代码中使用append。虽然在这种情况下没有问题,但您可能希望了解差异:append vs. extend并在大多数情况下坚持append

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

current[index] = guess

答案 1 :(得分:0)

以下是它应该如何亲爱的!

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")