简体   繁体   English

Python-copy.copy()的元素仍然与原始元素共享内存吗?

[英]Python - Elements of copy.copy() still share memory with the original one?

I wanted to make a copy of a list (literally a separated clone that has nothing sharing with the original). 我想复制一个列表(实际上是一个分离的克隆,与原始副本没有任何共享)。 I used copy.copy() and created 2 separated lists, but why does the elements of each copy still seem to share? 我使用了copy.copy()并创建了2个单独的列表,但是为什么每个副本的元素似乎仍然共享?

It's hard to explain, please check out the following output. 很难解释,请查看以下输出。

>>> a = [[0,1], [2,3]]
>>> import copy
>>> b = copy.copy(a)
>>> temp = b.pop()
>>> temp
[2, 3]
>>> a
[[0, 1], [2, 3]]
>>> b
[[0, 1]]
>>> temp.append(4)
>>> temp
[2, 3, 4]
>>> a
[[0, 1], [2, 3, 4]]
>>> b
[[0, 1]]

As you see, temp is popped from b , yet when I changed temp (aka append new stuff) then the data in a also changed. 如您所见, tempb弹出,但是当我更改temp (又名追加新内容)时, a中的数据也发生了变化。

My question is: Is this an expecting behavior of deepcopy? 我的问题是:这是预期的Deepcopy行为吗? How can I make a totally separate copy of a list then? 那我怎样才能制作一个完全独立的清单副本?

P/S: As the above example, I guess I can do P / S:作为上面的示例,我想我可以做
temp = copy.copy(b.pop())
but is this a proper way? 但这是正确的方法吗? Is there any other way to do what I want? 还有其他方法可以做我想要的吗?

P/S 2: This also happens when I use b = a[:] P / S 2:当我使用b = a [:]时,也会发生这种情况

Thanks! 谢谢!

friendly dog commented under the OP and suggested me to use deepcopy(). 友善的狗在OP下发表了评论,建议我使用deepcopy()。 It works. 有用。 Thanks! 谢谢!

You should use deepcopy() there because the copy() makes shallow clone of the object that you are referencing not the object inside it.If you want the whole object(with the object inside it) use deepcopy() instead. 你应该在那儿使用deepcopy(),因为copy()会使引用对象的浅表克隆而不是对象内部的对象,如果想要整个对象(包含对象的内部),请使用deepcopy()代替。

Please refer the links for better understanding 请参考链接以更好地了解

What is the difference between a deep copy and a shallow copy? 深层副本和浅层副本有什么区别?

https://docs.python.org/2/library/copy.html https://docs.python.org/2/library/copy.html

The copy.copy() was shallow copy. copy.copy()是浅表副本。 That means, it would create a new object as same as be copied. 这意味着,它将创建一个与复制对象相同的新对象。 but the elements within copied object didn't be created, and them also is a reference. 但是未创建复制对象中的元素,它们也是参考。 -> a = [[0,1], [2,3]] -> import copy -> b = copy.copy(a) # the b be created, but [0,1] [2,3] still are reference -> temp = b.pop() -> temp [2, 3] -> a [[0, 1], [2, 3]] -> b [[0, 1]] -> temp.append(4) -> temp [2, 3, 4] -> a [[0, 1], [2, 3, 4]] -> b [[0, 1]] Docs -> a = [[0,1], [2,3]] -> import copy -> b = copy.copy(a) # the b be created, but [0,1] [2,3] still are reference -> temp = b.pop() -> temp [2, 3] -> a [[0, 1], [2, 3]] -> b [[0, 1]] -> temp.append(4) -> temp [2, 3, 4] -> a [[0, 1], [2, 3, 4]] -> b [[0, 1]] 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM