gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:54:46 24 4
gpt4 key购买 nike

我试图理解为什么具有不同值的元素具有相同的 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 的元素分配给变量元组,则不会重用 idid(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com