切片操作会给我一个深拷贝还是浅拷贝?

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

这篇关于切片操作会给我一个深拷贝还是浅拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:切片操作会给我一个深拷贝还是浅拷贝?

基础教程推荐