python list.copy浅层复制与深层复制 [英] python list.copy shallow vs deep copy

查看:97
本文介绍了python list.copy浅层复制与深层复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我不理解浅拷贝的定义...但是我很困惑:

Maybe I don't understand the definition of shallow copy... but i'm very confused:

来自文档:

其中"s"是列表(但相同的问题分别适用于字典).

Where "s" is a list (but same question applies to dictionaries respectively).

"s.copy()|创建s的浅表副本(与s [:]相同)"

"s.copy() | creates a shallow copy of s (same as s[:])"

除了我认为s[:]是一个深层副本.例如,有关如何复制列表的信息,请参见此堆栈溢出答案 (没有它就指向原始版本).而且,使用list1.copy()似乎可以进行深层复制,并且与[:]

Except I thought s[:] was a deep copy. For example, see this stack overflow answer on how to copy a list (without it just pointing to the original version). And using list1.copy() seems to do a deep copy as well aka same behaviour as [:]

l1 = [1,2,3,4]
l2 = l1[:]
l3 = l1.copy()



l2.append(5)
l3[0] = 99
print(l1)
print(l2)
print(l3)
>> [1,2,3,4]
>> [1,2,3,4,5]
>> [99,2,3,4]

看来l1l2l3都是分开的对象.我想念什么?

It would appear that l1,l2, and l3 are all separate objects. What am I missing?

推荐答案

在这种情况下,您只是误解了浅"和深"的含义.

You've simply misunderstood what "shallow" and "deep" mean in this context.

浅表副本仅是顶级元素的副本.如果这些元素中的任何一个本身就是列表,则副本仍将引用原始列表. l1[:]l1.copy()都是这样做的.

A shallow copy is a copy of the top level of elements only. If any of those elements are themselves lists, the copies will still refer to the original lists. This is what both l1[:] and l1.copy() do.

深层副本是所有级别的副本.如果任何元素是列表,它们也将被深复制.没有参考将被共享.这就是copy.deepcopy()的作用.

A deep copy is a copy at all levels. If any of the elements are lists, they will also be deep copied. No references will be shared. This is what copy.deepcopy() does.

这篇关于python list.copy浅层复制与深层复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆