不可变的 numpy 数组?

发布于 2024-10-29 06:15:04 字数 93 浏览 1 评论 0原文

有没有一种简单的方法来创建不可变的 NumPy 数组?

如果必须从 ndarray 派生一个类来执行此操作,那么为了实现不变性而必须重写的最小方法集是什么?

Is there a simple way to create an immutable NumPy array?

If one has to derive a class from ndarray to do this, what's the minimum set of methods that one has to override to achieve immutability?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

疯狂的代价 2024-11-05 06:15:04

您可以使 numpy 数组不可写:

a = np.arange(10)
a.flags.writeable = False
a[0] = 1
# Gives: ValueError: assignment destination is read-only

另请参阅此线程中的讨论:

http://mail.scipy.org/pipermail/numpy-discussion/2008-December/039274.html

和文档:

http://docs.scipy.org/doc/numpy/reference/ generated/numpy.ndarray.flags.html

You can make a numpy array unwriteable:

a = np.arange(10)
a.flags.writeable = False
a[0] = 1
# Gives: ValueError: assignment destination is read-only

Also see the discussion in this thread:

http://mail.scipy.org/pipermail/numpy-discussion/2008-December/039274.html

and the documentation:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html

蛮可爱 2024-11-05 06:15:04

直接设置标志对我来说不起作用,但使用 < code>ndarray.setflags 确实有效:

a = np.arange(10)
a.setflags(write=False)
a[0] = 1  # ValueError

Setting the flag directly didn't work for me, but using ndarray.setflags did work:

a = np.arange(10)
a.setflags(write=False)
a[0] = 1  # ValueError
池予 2024-11-05 06:15:04

我在这个要点上有一个 Array 的子类: https://gist.github.com/sfaleron/9791418d7023a9985bb803170c5d93d8< /a>

它会复制其参数并将其标记为只读,因此如果您非常谨慎,那么您只能搬起石头砸自己的脚。我的直接需求是它是可散列的,这样我就可以成组使用它们,这样也可以。代码不多,但大约 70% 的行是用于测试的,所以我不会直接发布。

请注意,它不是直接替代品;它不会像普通数组构造函数那样接受任何关键字参数。不过,实例的行为类似于数组。

I have a subclass of Array at this gist: https://gist.github.com/sfaleron/9791418d7023a9985bb803170c5d93d8

It makes a copy of its argument and marks that as read-only, so you should only be able to shoot yourself in the foot if you are very deliberate about it. My immediate need was for it to be hashable, so I could use them in sets, so that works too. It isn't a lot of code, but about 70% of the lines are for testing, so I won't post it directly.

Note that it's not a drop-in replacement; it won't accept any keyword args like a normal Array constructor. Instances will behave like Arrays, though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文