NumPy resize方法

2024-05-13 19:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能给我解释一下吗?(Python 3.3.2,numpy 1.7.1版):

>>> a = np.array([[1,2],[3,4]])
>>> a    # just a peek
array([[1, 2],
       [3, 4]])
>>> a.resize(3,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot resize an array references or is referenced
by another array in this way.  Use the resize function
>>> a = np.array([[1,2],[3,4]])
>>> a.resize(3,2)
>>> a
array([[1, 2],
       [3, 4],
       [0, 0]])
>>> a = np.array([[1,2],[3,4]])
>>> print(a)   # look properly this time
[[1 2]
 [3 4]]
>>> a.resize(3,2)
>>> a
array([[1, 2],
       [3, 4],
       [0, 0]])

为什么看一眼数组就会创建对它的引用?(或者,至少,为什么在我完成查找之后,这个引用仍然存在?) 另外,这只是我的问题,还是这个异常需要重写一下?


Tags: innumpymostnpstdincallthisarray
1条回答
网友
1楼 · 发布于 2024-05-13 19:25:24

来自documentation(强调我的):

The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.

print不同,您的“peek”不会在之后减少引用计数。这是因为,在解释器中,最后一次计算的结果被分配给_。尝试:

print(_) # shows array
a.resize((3, 2), refcheck=False) # works

或者,如果您在两者之间进行任何其他计算(例如,1 + 2),这将从_中取消对数组的引用。

相关问题 更多 >