切片操作给我一个深或浅的副本? [英] 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.
但是当我编写代码的例子:
But when I write code for example:
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?
推荐答案
您正在创建一个浅复制,因为嵌套值不会被复制,只是被引用。
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
在这里,不复制嵌套的字典;它仅由两个列表引用。
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
这篇关于切片操作给我一个深或浅的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!