嗨任何人都可以解釋爲什麼我們有以下行爲:Python的字典missmatch
>>> k = [0.5, 1, 2]
>>> m = [0.5, 1, 2]
>>> dict1 = dict.fromkeys(k, dict.fromkeys(m, 0))
>>> dict1
{0.5: {0.5: 0, 1: 0, 2: 0}, 1: {0.5: 0, 1: 0, 2: 0}, 2: {0.5: 0, 1: 0, 2: 0}}
>>> dict1[0.5][0.5]= 4.5
>>> dict1
{0.5: {0.5: 4.5, 1: 0, 2: 0}, 1: {0.5: 4.5, 1: 0, 2: 0}, 2: {0.5: 4.5, 1: 0, 2: 0}}
>>> dict2 = {0.5: {0.5: 0, 1: 0, 2: 0}, 1: {0.5: 0, 1: 0, 2: 0}, 2: {0.5: 0, 1: 0, 2: 0}}
>>> dict2[0.5][0.5] = 4.5
>>> dict2
{0.5: {0.5: 4.5, 1: 0, 2: 0}, 1: {0.5: 0, 1: 0, 2: 0}, 2: {0.5: 0, 1: 0, 2: 0}}
所以在第一種情況下,每當我試圖改變dict1所有值的值具有相同第二個關鍵正在改變(例如dict1 [0.5] [0.5] = 4.5也會由於某些原因改變dict1 [1] [0.5])。
由於'dict.fromkeys(m,0)'運行一次,然後在'dict.fromkeys(k,dict.fromkeys(m,0))'的每個值中放入相同的字典。你可以通過在dict1中使用dct來檢查:print id(dct)''它們都是相同的'id',例如。相同的'對象' – TemporalWolf
只創建了一個子字典。你現在擁有的詞典本身可以通過多種方式訪問。 'dict [0.5]'和'dict [1]'是指同一個字典(而不是它的拷貝) – sgrg