【问题标题】:Dictionary copy() - is shallow deep sometimes?字典复制() - 有时很浅?
【发布时间】:2019-03-26 23:48:34
【问题描述】:

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

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

dict1_alias = dict1
dict1_shallow_copy = dict1.copy()

我的理解是,如果我们deldict1 的一个元素,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'}  

我错过了什么?

【问题讨论】:

  • 即使是浅拷贝也是拷贝,不是同一个对象。
  • "现在如果我们删除 dict1 的一个元素,dict1_alias 和 dict1_shallow_copy 都应该受到影响。"不,绝对不是。它们是不同的dict对象,这就是为什么它们是副本

标签: python-3.x deep-copy shallow-copy


【解决方案1】:

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

>>> 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

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2016-12-14
    • 2015-08-11
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2013-01-24
    • 2016-07-21
    相关资源
    最近更新 更多