python 字典拷貝

(1)字典直接賦值給變量python

#!/usr/bin/env python3
dct = {"key1":"小白","key2":"小黑"}
dct_1 = dct
dct_1['key2'] = "小灰"
print(dct) # {'key1': '小白', 'key2': '小灰'}

你會發現這種賦值方式,dct_1改變後,dct也跟着改變。這是由於字典賦值是引用性賦值,賦的是地址。app

(2)dict.copy() 對象拷貝,淺拷貝spa

#!/usr/bin/env python3
dct = {'key1':'小白','key2':['小黑']}
dct_1 = dct.copy()
dct_1['key1'] = '小灰'
print(dct) # {'key1': '小白', 'key2': '小黑'}

dct_1['key2'].append('小紅')
print(dct) #{'key1': '小白', 'key2': ['小黑', '小紅']}

copy雖然修改key1不會影響原數據(返過來也同樣),可是修改key2會影響。由於key2的值仍然是地址(列表賦值也是引用賦值)。code

(3)deepcopy(dict) 對象拷貝,深拷貝對象

#!/usr/bin/env python3
import copy
dct = {'key1':'小白','key2':['小黑']}
dct_1 = copy.deepcopy(dct)
dct_1['key1'] = '小灰'
print(dct) # {'key1': '小白', 'key2': '小黑'}

dct_1['key2'].append('小紅')
print(dct) #{'key1': '小白', 'key2': ['小黑']}

深拷貝,不管你怎麼修改,都不會相互影響。使用時請根據需求注意選擇合適的方法blog

相關文章
相關標籤/搜索