不可变的 numpy 数组?
有没有一种简单的方法来创建不可变的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使 numpy 数组不可写:
另请参阅此线程中的讨论:
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:
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
直接设置标志对我来说不起作用,但使用 < code>ndarray.setflags 确实有效:
Setting the flag directly didn't work for me, but using
ndarray.setflags
did work:我在这个要点上有一个 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.