2016-05-01 5 views
0
temp={} 
L=[2,4,6] 
temp[0]=[1,2,3] #ignore 
temp[1]=[4,5,6] #ignore 
L.insert(1,3)  
temp[2]=L 
print(temp[2]) #before insert 
L.insert(2,3) 
temp[3]=L 
print(temp[3]) 
print(temp[2]) #after insert 

TEMP [2]変数は、それが第二の挿入操作後の値だ保持していない後の値を保持しません。むしろ、それは私の意見では、この操作の影響を受けるべきではない、新しい値のLを取ります。パイソン:2-D変数は、「挿入」オペレーション

tempの値の違いは、1つ前と後のprint文の違いを見ることができます。

もし誰でもできるのであれば、バックエンドで何が起こっているのか正確に説明してください。私はPython(2日齢の学習者)には全く新しいので、どんな助けでも大歓迎です。

答えて

0

唯一つのリストは、あなたがそれを保存したり、それを修正するかどうか、それはまだ同じリストです、あなたのコードである:

temp = {} # create a dictionary "temp" 
L = [2, 4, 6] # create a list "L" 
L.insert(1, 3) # insert elements into list that "L" names 
temp[2] = L # add what "L" names into the dictionary (not a copy) 
print(temp[2]) # print that same dictionary value 
L.insert(2, 3) # modify the list that "L" names 
temp[3] = L # insert that same list into the dictionary under a new key (not a copy) 
print(temp[3]) # print that same dictionary value 
print(temp[2]) # print the previous dictionary value 

あなたはその現在の状態を保存したい場合は、あなたがそれをコピーする必要があります:

... 
temp[2] = list(L) # add a copy of what "L" names into the dictionary 
print(temp[2]) # print that same dictionary value 
L.insert(2, 3) # modify the original list that "L" names 
temp[3] = list(L) # insert that a copy of the modified list into the dictionary under a new key 
print(temp[3]) # print that same dictionary value 
print(temp[2]) # print the previous dictionary value 

プログラムは正しいことを行いました。少しの調整が必要なあなたの期待です。