2017-03-15 51 views
1

我試圖修改臨時列表並將temp列表存儲在可能的列表中,但我需要讓list1保持不變。當我通過Python運行它時,我的臨時列表沒有改變,所以我想知道哪裏出了問題。在Python中修改列表中的列表

list1 = [['1', '1', '1'], 
    ['0', '0', '0'], 
    ['2', '2', '2']] 

temp = list1 
possible = [] 

for i in range(len(temp)-1): 
    if(temp[i][0] == 1): 
      if(temp[i+1][0] == 0): 
        temp[i+1][0] == 1 

possible = possible + temp 
temp = list1 

print(possible) 
+1

'temp = list1'不是副本。你根本沒有創建一個臨時列表。請參閱https://nedbatchelder.com/text/names.html – user2357112

+2

使用'=',而不是'=='。 –

回答

0

對於list1陣列複製到temp因爲,list1是2D陣列,由其他人所建議的,我們可以使用deepcopy。請參閱this link here.。或者,它可以使用列表理解以及here所示完成。

陣列具有作爲string元件,所以條件語句if(temp[i][0] == 1)if(temp[i+1][0] == 0)可以通過if(temp[i][0] == '1')if(temp[i+1][0] == '0')代替。並且如上面在評論temp[i+1][0] == 1中提到的必須被temp[i+1][0] = 1替換。您可以嘗試以下方法:

from copy import deepcopy 

list1 = [['1', '1', '1'], 
     ['0', '0', '0'], 
     ['2', '2', '2']] 

# copying element from list1 
temp = deepcopy(list1) 
possible = [] 
for i in range(len(temp)-1): 
    if(temp[i][0] == '1'): 
     if(temp[i+1][0] == '0'): 
      temp[i+1][0] = '1' 


possible = possible + temp 

print('Contents of possible: ', possible) 
print('Contents of list1: ', list1) 
print('Contents of temp: ', temp)