python - 可视化深拷贝和浅拷贝之间的差异
问题描述
我明白深拷贝和浅拷贝有什么区别。
深拷贝将一个对象复制到另一个对象中。这意味着如果您对对象的副本进行更改,它不会影响原始对象。在 Python 中,我们为此使用函数 deepcopy(),并导入模块副本。我们像这样使用它:
为了可视化它,我使用了 python 导师并得到了这个,
import copy
a = [1, 2, 3]
b = copy.deepcopy(a)
这是有道理的,因为它在我使用deepcopy()
函数时创建了一个新对象。
另一方面,浅拷贝是,
然而,浅拷贝将一个对象的引用复制到另一个对象。因此,如果我们在副本中进行更改,它将影响原始对象。为此,我们有函数 copy()。
但是当我使用浅拷贝时,为什么会得到相同的结果?
import copy
a = [1, 2, 3]
b = copy.deepcopy(a)
c = copy.copy(a)
据我了解,浅拷贝应该引用同一个对象(即a
,而不是创建一个新对象如下,
c = a
有人可以告诉我为什么deepcopy()
浅拷贝和浅拷贝都创建一个新对象吗?
解决方案
copy
makes a copy of the parent object only. It makes a new object that points to all the same attributes as the original object. deepcopy
- 1) copies the original object, 2) then runs copy
on each attribute pointed to, then makes copies of any attributes that those other copies point to etc....
In your case, since the attributes of your list are immutable, copy and deepcopy are interchangeable. if you have a list of lists, or list of lists of lists or ... then you use deepcopy.
Here is a quick example of the difference:
>>> example = [[1, 2, 3], [4, 5, 6]]
>>> same_obj = example
>>> shallow_copy = copy(example)
>>> deep_copy = deepcopy(example)
>>> example.append([7, 8, 9])
>>> print(example)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(same_obj)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(shallow_copy)
[[1, 2, 3], [4, 5, 6]]
>>> example[0].sort(reverse=True)
>>> print(example)
[[3, 2, 1], [4, 5, 6], [7, 8, 9]]
>>> print(shallow_copy)
[[3, 2, 1], [4, 5, 6]]
>>> print(deep_copy)
[[1, 2, 3], [4, 5, 6]]
shallow_copy
and example
are two different objects. They have indexes which point to other objects (in this case, lists). These indexes are all pointing to the same objects, so if you mutate the object that either list points to, the mutation shows up in both lists. deepcopy
, not only copied the parent list, but also copied each list that the parent list pointed to. so any changes to a sub-list did not affect deep_copy
in any way.
推荐阅读
- lua - 如何修复“stdin:1:尝试对 nil 值(全局'lua')执行算术”错误?
- python-3.x - 当数据框中其他列的条件匹配时,从一列中提取单元格
- swift - 如何更改 SKScene 的背景颜色?
- laravel - 我在 Laravel 中执行此查询时出错
- r - dplyr - 过滤器:限制可用于生成逻辑的函数?
- sql - 使用连接和条件聚合的 SQL 更新
- microsoft-graph-api - MSGraph 消息 api 附件 ID 正在更改
- c# - 如果我使用路径库,图像不会从 wwwroot 加载
- python - 运行 pip install mysql-python 时出错:"python setup.py egg_info" failed with error code 1
- sql-server-2012 - SQL Pivot 双倍总和