嘿,在這裏,我試圖備份game_list中的每個變化到game_list_bkp。 我希望我可以將while循環中發生的每個更改附加到game_list_bkp。但是如果循環運行4次,它只會追加4個相同的列表到game_list_bkp。我得到結果等[[3, 7, 8, 6], [3, 7, 8, 6], [3, 7, 8, 6], [3, 7, 8, 6]]
但我需要導致像[[3], [3, 7], [3, 7, 8], [3, 7, 8, 6]]
問題在Python中的while循環的追加列表中
import random
val = True
game_list = []
game_list_bkp = []
usr_input = 1
while usr_input <5:
if usr_input >0:
game_list.append(random.randint(1,9))
game_list_bkp.append(game_list)
print (game_list_bkp)
if usr_input !=0:
usr_input = int(input("Enter:"))
else:
val=False
結果
[[3]]
輸入:1
[[3,7],[ 3,7]]
請輸入:1
[[3,7,8],[3,7,8],[3,7,8]]
輸入:1
[[3,7,8,6],[ 1,3,7,8,6],[3,7,8,6],[3,7,8,6]]
做BC你添加一個裁判GAME_LIST不行 - 你需要的時候做出的一個副本(使用list.copy()或不服喜歡) - 見https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list –