python - numpy数组的多个元素具有相同的id

标签 python numpy memory-management

我试图理解为什么具有不同值的元素具有相同的id。有人可以向我解释一下 NumPy 中内存管理的情况吗?下面的例子

import numpy as np
x=np.array([1,2,3,4])
print([id(a) for a in x])
[140718968034552, 140719258631960, 140718968034552, 140719258631960]

这里,第一个和第三个元素具有相同的 id(140718968034552),尽管它们具有不同的数值。与第二个和第四个元素相同。

最佳答案

In [54]: x=np.array([1,2,3,4])
In [55]: [type(a) for a in x]
Out[55]: [numpy.int64, numpy.int64, numpy.int64, numpy.int64]
In [56]: [id(a) for a in x]
Out[56]: [140147220886728, 140147220887808, 140147220886728, 140147220887808]

小整数的 id 是唯一的,但这不是数组包含的内容:

In [57]: [type(a) for a in x.tolist()]
Out[57]: [int, int, int, int]
In [58]: [id(a) for a in x.tolist()]
Out[58]: [10914496, 10914528, 10914560, 10914592]
In [59]: id(2)
Out[59]: 10914528

获取 int 对象的另一种方法:

In [60]: [id(a.item()) for a in x]
Out[60]: [10914496, 10914528, 10914560, 10914592]

编辑

如果我将 x 的元素分配给变量元组,则 id 不会被重用。 id(x0) 仍在使用中,因此 id(x2) 无法使用它。 Out[56] 中的更改只是解释器重用内存的产物。

In [73]: x0,x1,x2,x3 = x
In [74]: id(x0),id(x1),id(x2),id(x3)
Out[74]: (140146931335720, 140146931335504, 140146931335600, 140146931335576)
In [75]: type(x0)
Out[75]: numpy.int64

关于python - numpy数组的多个元素具有相同的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63891689/

相关文章:

Python pywin32 - VK_SLEEP 按下不工作

python - 为什么 matplotlib 等高线图在绘制二维数组时失败

python - 具有 NA 的两列的条件最小值

ios - 新iPad : Low Memory Warnings Not Appearing?

python - Peewee 别名不起作用并抛出 AttributeError

python - lxml pretty_print python内存过载

python - 根据向量绘制数组中的对象

c - free() 错误(使用 valgrind 调试)?

Iphone:在哪里释放对象?

python - 如何处理协程函数的多个结果?