2017-11-11 47 views
-1

嘿,在这里,我试图备份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]]

+1

做BC你添加一个裁判GAME_LIST不行 - 你需要的时候做出的一个副本(使用list.copy()或不服喜欢) - 见https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list –

回答

1

您需要每次追加game_list的副本。您可以通过附加game_list[:]代替game_list

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 
+0

Thnak你Wodin! –