简体   繁体   English

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

[英]Multiple elements of numpy array has same id

I am trying to understand why elements with different value have the same id .我试图理解为什么具有不同值的元素具有相同的id Could someone explain me what is going with respect to memory management in NumPy.有人可以向我解释一下 NumPy 中内存管理的情况。 Example below下面的例子

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

Here, first and the third element has the same id (140718968034552) though they hold different numerical values.这里,第一个和第三个元素具有相同的id (140718968034552),尽管它们拥有不同的数值。 Same as for second and fourth elements.与第二个和第四个元素相同。

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]

The id of small integers is unique, but that's not what the array contains:小整数的 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

Another way to get the int objects:获取int对象的另一种方法:

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

edit编辑

If I assign the elements of x to a tuple of variables, the id are not reused.如果我将x的元素分配给变量元组,则不会重用id id(x0) is still in use, so id(x2) cannot take it. id(x0)仍在使用中,因此id(x2)无法接受。 The alteration in Out[56] is just an artifact of memory reuse by the interpreter. 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

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

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