Numpy: arr[...,0,:] 有效。但是如何存储切片命令 (..., 0, :) 中包含的数据呢?

发布于 2024-11-26 03:00:40 字数 94 浏览 1 评论 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 技术交流群。

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

发布评论

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

评论(5

沙沙粒小 2024-12-03 03:00:40

Python 根据切片语法创建特殊对象,但仅在方括号内用于索引。您可以手动创建这些对象(在本例中,(...,0,:)(Ellipsis, 0, slice(None, None, None)),或者你可以创建一个小辅助对象:

class ExtendedSliceMaker(object):
    def __getitem__(self, idx):
        return idx

>>> ExtendedSliceMaker()[...,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:

class ExtendedSliceMaker(object):
    def __getitem__(self, idx):
        return idx

>>> ExtendedSliceMaker()[...,0,:]
(Ellipsis, 0, slice(None, None, None))
星星的轨迹 2024-12-03 03:00:40

在 NumPy 中使用 s_:

In [1]: np.s_[...,0,:]
Out[1]: (Ellipsis, 0, slice(None, None, None))

Use s_ in NumPy:

In [1]: np.s_[...,0,:]
Out[1]: (Ellipsis, 0, slice(None, None, None))
微凉 2024-12-03 03:00:40

相当于 (...,0,:) 应该是...

>>> myslice = (..., 0, slice(None, None))
>>> myslice
(Ellipsis, 0, slice(None, None, None))

The equivalent to (...,0,:) should be...

>>> myslice = (..., 0, slice(None, None))
>>> myslice
(Ellipsis, 0, slice(None, None, None))
始终不够 2024-12-03 03:00:40

Python 的巧妙之处在于,您实际上可以创建一个类来检查这些事物的表示方式。 Python 使用魔术方法 __getitem__ 来处理索引操作,因此我们将创建一个重载该方法的类,以向我们显示传入的内容,实例化该类,然后“索引”到该实例

class foo:
  def __getitem__(self, index): print index

foo()[...,0,:]

:我们的结果是:

(Ellipsis, 0, slice(None, None, None))

Ellipsisslice 是内置函数,我们可以阅读它们的文档:

help(Ellipsis)
help(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:

class foo:
  def __getitem__(self, index): print index

foo()[...,0,:]

And our result is:

(Ellipsis, 0, slice(None, None, None))

Ellipsis and slice are builtins, and we can read their documentation:

help(Ellipsis)
help(slice)
蹲在坟头点根烟 2024-12-03 03:00:40

我认为您只想执行 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])

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