字典副本() - 有时深浅吗?

问题描述 投票:2回答:1

根据the official docs,字典副本很浅,即它返回一个包含相同键值对的新字典:

dict1 = {1: "a", 2: "b", 3: "c"}

dict1_alias = dict1
dict1_shallow_copy = dict1.copy()

我的理解是,如果我们del dict1的元素,dict1_alias和dict1_shallow_copy都应该受到影响;然而,深度镜检不会。

del dict1[2]
print(dict1)
>>> {1: 'a', 3: 'c'}  
print(dict1_alias)
>>> {1: 'a', 3: 'c'} 

dict1_shallow_copy第二元素仍在那里!

print(dict1_shallow_copy)
>>>  {1: 'a', 2: 'b', 3: 'c'}  

我错过了什么?

python-3.x deep-copy shallow-copy
1个回答
3
投票

浅拷贝意味着元素本身是相同的,而不是字典本身。

>>> a = {'a':[1, 2, 3],  #create a list instance at a['a']
         'b':4,
         'c':'efd'}
>>> b = a.copy()         #shallow copy a
>>> b['a'].append(2)     #change b['a']
>>> b['a']
[1, 2, 3, 2]
>>> a['a']               #a['a'] changes too, it refers to the same list
[1, 2, 3, 2]             
>>> del b['b']           #here we do not change b['b'], we change b
>>> b
{'a': [1, 2, 3, 2], 'c': 'efd'}
>>> a                    #so a remains unchanged
{'a': [1, 2, 3, 2], 'b': 4, 'c': 'efd'}1
© www.soinside.com 2019 - 2024. All rights reserved.