今天寫**遇到乙個字典更新的問題。
直接上**:
# coding:utf-8
import collections
import numpy as np
a = np.array(([
1,2]
,[3,
4]))
b = collections.ordereddict(
)c = collections.ordereddict(
)for i in
range
(a.shape[0]
):b[
'x']
= a[i][0
] b[
'y']
= a[i][1
] c[
str(i)
]= b
for key,value in c.items():
print
(key, value)
列印結果居然是:
0 ordereddict([(
'x',3)
,('y',4)
])1 ordereddict([(
'x',3)
,('y',4)
])
這個現象很神奇,就是說明明寫了乙個c字典,正常情況下應該輸出的是:
0 ordereddict([(
'x',1)
,('y',2)
])1 ordereddict([(
'x',3)
,('y',4)
])
研究了半天,真是沒有頭緒。
後來查了一下,終於明白python中一切皆引用,也就意味著,當將b賦值給c的時候,其實不是真正的賦值操作,而是將b的位址給了c,那麼當b在第二次迴圈的時候,b中的內容發生了改變,那麼c中之前賦值操作的內容也會發生改變。最好的方式就是直接列印出位址看一下就好了:
# coding:utf-8
import collections
import numpy as np
a = np.array(([
1,2]
,[3,
4]))
c = collections.ordereddict(
)b = collections.ordereddict(
)for i in
range
(a.shape[0]
):b[
'x']
= a[i][0
] b[
'y']
= a[i][1
] c[
str(i)
]= b
print(id
(b),
id(c[
str(i)])
)
2304502297544
2304502297544
2304502297544
2304502297544
也就是說,c中的兩個鍵都存的是b的位址,所以,其實折騰來折騰去其實是對同一塊記憶體的修改。
這裡其實有兩個問題:
如果用全域性變數,那麼用b的深拷貝。
b應該作為區域性變數進行賦值
用b的深拷貝:
import collections
import numpy as np
a = np.array(([
1,2]
,[3,
4],[
5,6]
,[7,
8]))
c = collections.ordereddict(
)b = collections.ordereddict(
)for i in
range
(a.shape[0]
):b[
'x']
= a[i][0
] b[
'y']
= a[i][1
] c[
str(i)
]= b.copy(
)print(id
(b),
id(c[
str(0)
]),id
(b),
id(c[
str(1)
]))for key,value in c.items():
print(id
(c[key]))
print
(key, value)
2433414755272
2433414755400
2433414755272
2433414755528
2433414755400
0 ordereddict([(
'x',1)
,('y',2)
])2433414755528
1 ordereddict([(
'x',3)
,('y',4)
])
可以看到,c的兩個內容位址是不一樣的,而且也與b不一樣。這個過程就是每次迴圈都真正生成了另外乙個物件來儲存b中的內容,這樣即使b發生了改變,另外乙個物件也不會發生改變,因為兩者是不同的物件。
將b換做區域性變數:
import collections
import numpy as np
a = np.array(([
1,2]
,[3,
4]))
c = collections.ordereddict(
)for i in
range
(a.shape[0]
):b = collections.ordereddict(
) b[
'x']
= a[i][0
] b[
'y']
= a[i][1
] c[
str(i)
]= b
for key,value in c.items():
print(id
(c[key]))
print
(key, value)
輸出如下:
2487731450824
0 ordereddict([(
'x',1)
,('y',2)
])2487731450952
1 ordereddict([(
'x',3)
,('y',4)
])
可以看到,每次的b都是不同的,因此c中儲存的內容也是不同的。 python字典len d Python字典詳解
python字典 dict 是乙個很常用的復合型別,其它常用符合型別有 陣列 array 元組 touple 和集合 set 字典是乙個key value的集合,key可以是任意可被雜湊 內部key被hash後作為索引 的型別。因此,key可以是文字 數字等任意型別。如果兩個數字 判斷相等,那麼ke...
python字典換行輸出 Python字典如何換行
python字典如何換行 python字典換行的方法如下 1 換行時保證行尾是逗號即可a key2 val2 key3 val3 key4 val4 key5 val5 注意這種情況下,每一行第乙個非空白字元都要和第一行的括號後的字元對齊,並且最後的括號是不換行 直接跟在最後乙個元素後面 的。3 另...
python實現字典排序 python 字典排序
引子 字典,形如 dic 字典中的元素沒有順序,所以dic 0 是有語法錯誤的。並且不可以有重複的鍵值,所以 dic.add c 4後,字典變成 待解決問題 如何根據需要可以根據 鍵 或 鍵值 進行不同順序的排序?函式原型 sorted dic,value,reverse dic為比較函式,valu...