2017-03-15 2 views
1

私は一時リストを修正し、一時リストを可能なリストに格納しようとしていますが、list1は変更しないでください。これをPythonで実行したとき、私の一時的なリストは変更されていないので、どこが間違っているのだろうかと思います。 list1、以降templist1の配列をコピーするためリスト内のリストを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

は他人によって示唆されるように、我々はdeepcopyを使用することができ、2次元アレイです。 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] == 1temp[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) 
関連する問題