Does a slicing operation give me a deep or shallow copy?(切片操作会给我一个深拷贝还是浅拷贝?)
问题描述
官方 Python 文档说在 Python 中使用切片运算符和赋值制作切片列表的浅表副本.
The official Python docs say that using the slicing operator and assigning in Python makes a shallow copy of the sliced list.
但是当我写代码例如:
o = [1, 2, 4, 5]
p = o[:]
当我写的时候:
id(o)
id(p)
我得到不同的 id,并且附加一个列表不会反映在另一个列表中.是不是在创建深拷贝,还是我哪里出错了?
I get different id's and also appending one one list does not reflect in the other list. Isn't it creating a deep copy or is there somewhere I am going wrong?
推荐答案
您正在创建一个 浅 副本,因为嵌套值不会被复制,而只是被引用.deep 副本也会创建列表引用的值的副本.
You are creating a shallow copy, because nested values are not copied, merely referenced. A deep copy would create copies of the values referenced by the list too.
演示:
>>> lst = [{}]
>>> lst_copy = lst[:]
>>> lst_copy[0]['foo'] = 'bar'
>>> lst_copy.append(42)
>>> lst
[{'foo': 'bar'}]
>>> id(lst) == id(lst_copy)
False
>>> id(lst[0]) == id(lst_copy[0])
True
这里没有复制嵌套字典;它仅被两个列表引用.新元素 42 未共享.
Here the nested dictionary is not copied; it is merely referenced by both lists. The new element 42 is not shared.
请记住,Python 中的一切都是对象,名称和列表元素只是对这些对象的引用.列表的副本会创建一个新的外部列表,但新列表仅接收对完全相同的对象的引用.
Remember that everything in Python is an object, and names and list elements are merely references to those objects. A copy of a list creates a new outer list, but the new list merely receives references to the exact same objects.
适当的深拷贝会递归地创建列表中包含的每个对象的新副本:
A proper deep copy creates new copies of each and every object contained in the list, recursively:
>>> from copy import deepcopy
>>> lst_deepcopy = deepcopy(lst)
>>> id(lst_deepcopy[0]) == id(lst[0])
False
这篇关于切片操作会给我一个深拷贝还是浅拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:切片操作会给我一个深拷贝还是浅拷贝?
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
