Numpy: arr[...,0,:] 有效。但是如何存储切片命令 (..., 0, :) 中包含的数据呢?
在 Numpy(我想通常是 Python)中,如何存储切片索引,例如 (...,0,:),以便传递它并将其应用于各种数组?比如说,如果能够在函数之间传递切片索引,那就太好了。
In Numpy (and Python in general, I suppose), how does one store a slice-index, such as (...,0,:), in order to pass it around and apply it to various arrays? It would be nice to, say, be able to pass a slice-index to and from functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Python 根据切片语法创建特殊对象,但仅在方括号内用于索引。您可以手动创建这些对象(在本例中,
(...,0,:)
为(Ellipsis, 0, slice(None, None, None))
,或者你可以创建一个小辅助对象:Python creates special objects out of the slice syntax, but only inside the square brackets for indexing. You can either create those objects by hand (in this case,
(...,0,:)
is(Ellipsis, 0, slice(None, None, None))
, or you can create a little helper object:在 NumPy 中使用 s_:
Use s_ in NumPy:
相当于
(...,0,:)
应该是...The equivalent to
(...,0,:)
should be...Python 的巧妙之处在于,您实际上可以创建一个类来检查这些事物的表示方式。 Python 使用魔术方法 __getitem__ 来处理索引操作,因此我们将创建一个重载该方法的类,以向我们显示传入的内容,实例化该类,然后“索引”到该实例
:我们的结果是:
Ellipsis
和slice
是内置函数,我们可以阅读它们的文档:The neat thing about Python is that you can actually make a class to inspect how these things are represented. Python uses the magic method
__getitem__
to handle indexing operations, so we'll make a class that overloads this to show us what was passed in, instantiate the class, and "index in" to the instance:And our result is:
Ellipsis
andslice
are builtins, and we can read their documentation:我认为您只想执行 myslice = slice(1,2) 来定义一个将返回第二个元素的切片(即 myarray[myslice] == myarray[1:2])
I think you want to just do myslice = slice(1,2) to for example define a slice that will return the 2nd element (i.e. myarray[myslice] == myarray[1:2])