gpt4 book ai didi

python - 属性错误 : __enter__ when using numpy nditer inside the with statement

转载 作者:太空宇宙 更新时间:2023-11-04 02:18:14 24 4
gpt4 key购买 nike

我正在尝试遍历一个 numpy 数组并更改其中的一些值。这是我的代码,它是从文档 ( numpy nditer docs ) 中逐字复制的:

import numpy as np

a = np.arange(6).reshape(2,3)
print(a)
with np.nditer(a, op_flags=['readwrite']) as it:
for x in it:
x[...] = 2 * x

print(a)

但我不断收到以下回溯:

Traceback (most recent call last):
File "text.py", line 5, in <module>
with np.nditer(a, op_flags=['readwrite']) as it:
AttributeError: __enter__

是我做错了什么,还是文档中有错误(withnditer 的用法是否已弃用)?

最佳答案

您正在查看 Numpy 1.15 的文档,它使用了 new feature of nditer() introduced in that release :

Under certain conditions, nditer must be used in a context manager

When using an numpy.nditer with the "writeonly" or "readwrite" flags, there are some circumstances where nditer doesn’t actually give you a view of the writable array. Instead, it gives you a copy, and if you make changes to the copy, nditer later writes those changes back into your actual array. Currently, this writeback occurs when the array objects are garbage collected, which makes this API error-prone on CPython and entirely broken on PyPy. Therefore, nditer should now be used as a context manager whenever it is used with writeable arrays, e.g., with np.nditer(...) as it: .... You may also explicitly call it.close() for cases where a context manager is unusable, for instance in generator expressions.

该错误表明您使用的是早期版本的 Numpy; with 语句仅适用于上下文管理器must implement __exit__ (and __enter__) ,并且 AttributeError 异常表明在您的 Numpy 版本中不存在所需的实现。

要么升级,要么不使用 with:

for x in np.nditer(a, op_flags=['readwrite']):
x[...] = 2 * x

使用 CPython 时,您可能仍然会遇到导致 1.15 版本中所做更改的问题。使用 PyPy 时,您遇到这些问题,升级是您唯一正确的解决办法。

您可能想引用 1.14 version of the same documentation entry you used (或更具体地说,确保 pick the right documentation for your local version

关于python - 属性错误 : __enter__ when using numpy nditer inside the with statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52139518/

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