谁能给我解释一下? (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]])
为什么查看数组会创建对它的引用? (或者,至少,为什么在我完成查找后该引用仍然存在?) 另外,是我一个人还是那个异常需要重写一下?
最佳答案
来自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
toFalse
.
与 print
不同,您的“peek”不会在之后减少引用计数。这是因为,在解释器中,最后一次计算的结果被分配给 _
。尝试:
print(_) # shows array
a.resize((3, 2), refcheck=False) # works
或者,如果您在两者之间进行任何其他计算(例如只是 1 + 2
),这将从 _
中取消引用您的数组。
关于python - NumPy 调整大小方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20730366/