了解dict.copy()-浅还是深? [英] Understanding dict.copy() - shallow or deep?
问题描述
在阅读dict.copy()
的文档时,它说它制作了字典的浅表副本.我正在关注的书(Beazley的Python参考)也是如此,该书说:
While reading up the documentation for dict.copy()
, it says that it makes a shallow copy of the dictionary. Same goes for the book I am following (Beazley's Python Reference), which says:
m.copy()方法变浅 包含在其中的项目的副本 映射对象并将其放置在 新的映射对象.
The m.copy() method makes a shallow copy of the items contained in a mapping object and places them in a new mapping object.
考虑一下:
>>> original = dict(a=1, b=2)
>>> new = original.copy()
>>> new.update({'c': 3})
>>> original
{'a': 1, 'b': 2}
>>> new
{'a': 1, 'c': 3, 'b': 2}
所以我认为这也会更新original
的值(并添加'c':3),因为我正在执行浅表复制.就像您对列表进行操作一样:
So I assumed this would update the value of original
(and add 'c': 3) also since I was doing a shallow copy. Like if you do it for a list:
>>> original = [1, 2, 3]
>>> new = original
>>> new.append(4)
>>> new, original
([1, 2, 3, 4], [1, 2, 3, 4])
这按预期工作.
由于两者都是浅表副本,为什么dict.copy()
不能按我预期的那样工作?还是我对浅复制和深复制的理解存在缺陷?
Since both are shallow copies, why is that the dict.copy()
doesn't work as I expect it to? Or my understanding of shallow vs deep copying is flawed?
推荐答案
通过浅复制",这意味着字典的 content 不会按值复制,而只是创建一个新引用. /p>
By "shallow copying" it means the content of the dictionary is not copied by value, but just creating a new reference.
>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
相比之下,深层副本将按值复制所有内容.
In contrast, a deep copy will copy all contents by value.
>>> import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
所以:
-
b = a
:引用分配,使a
和b
指向同一对象.
b = a
: Reference assignment, Makea
andb
points to the same object.
b = a.copy()
:浅复制,a
和b
将成为两个孤立的对象,但它们的内容仍共享相同的引用
b = a.copy()
: Shallow copying, a
and b
will become two isolated objects, but their contents still share the same reference
b = copy.deepcopy(a)
:深层复制,a
和b
的结构和内容完全隔离.
b = copy.deepcopy(a)
: Deep copying, a
and b
's structure and content become completely isolated.
这篇关于了解dict.copy()-浅还是深?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!