为什么整数列表的Deepcopy在内存中返回相同的整数? [英] Why deepcopy of list of integers returns the same integers in memory?

查看:85
本文介绍了为什么整数列表的Deepcopy在内存中返回相同的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在课堂上了解到浅层副本和深层副本之间的区别。但是以下内容没有道理

I understand the differences between shallow copy and deep copy as I have learnt in class. However the following doesn't make sense

import copy

a = [1, 2, 3, 4, 5] 

b = copy.deepcopy(a)

print(a is b)
print(a[0] is b[0])
----------------------------
~Output~
>False
>True
----------------------------

不应 print(a [0] is b [0])将False视为对象及其组成部分元素是否在深拷贝中的其他内存位置重新创建?我只是在测试这点,因为我们已经在课堂上讨论了它,但似乎没有用。

Shouldn't print(a[0] is b[0]) evaluate to False as the objects and their constituent elements are being recreated at a different memory location in a deep copy? I was just testing this out as we had discussed this in class yet it doesn't seem to work.

推荐答案

在另一个答案中,这可能是由于Python包含了用于小整数的对象。虽然这个说法是正确的,但并不是导致这种现象的原因。

It was suggested in another answer that this may be due to the fact Python has interned objects for small integers. While this statement is correct, it is not what causes that behaviour.

让我们看看当我们使用更大的整数时会发生什么。

Let's have a look at what happens when we use bigger integers.

> from copy import deepcopy
> x = 1000
> x is deepcopy(x)
True

如果我们在 copy 模块,我们发现调用具有原子值的 deepcopy 会延迟对函数 _deepcopy_atomic

If we dig down in the copy module we find out that calling deepcopy with an atomic value defers the call to the function _deepcopy_atomic.

def _deepcopy_atomic(x, memo):
    return x

所以实际上发生的是 deepcopy 不会复制原子值,而只会返回它。

So what is actually happening is that deepcopy will not copy an atomic value, but only return it.

例如, int float str 函数等。

这篇关于为什么整数列表的Deepcopy在内存中返回相同的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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