如何在 Python 中使用省略号切片语法?

发布于 2024-07-05 17:11:31 字数 132 浏览 7 评论 0原文

这出现在 Python 的隐藏功能中,但我看不到好的文档或示例解释该功能的工作原理。

This came up in Hidden features of Python, but I can't see good documentation or examples that explain how the feature works.

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

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

发布评论

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

评论(5

凡间太子 2024-07-12 17:11:31

省略号...不是隐藏功能,它只是一个常量。 它与 javascript ES6 完全不同,它是语言语法的一部分。 没有内置类或 Python 语言结构使用它。

因此,它的语法完全取决于您或其他人是否编写了代码来理解它。

Numpy 使用它,如 文档。 一些示例此处

在你自己的类中,你可以像这样使用它:

>>> class TestEllipsis(object):
...     def __getitem__(self, item):
...         if item is Ellipsis:
...             return "Returning all items"
...         else:
...             return "return %r items" % item
... 
>>> x = TestEllipsis()
>>> print x[2]
return 2 items
>>> print x[...]
Returning all items

当然,有 Python 文档语言参考。 但这些并没有多大帮助。

Ellipsis, or ... is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it.

So the syntax for it depends entirely on you, or someone else, having written code to understand it.

Numpy uses it, as stated in the documentation. Some examples here.

In your own class, you'd use it like this:

>>> class TestEllipsis(object):
...     def __getitem__(self, item):
...         if item is Ellipsis:
...             return "Returning all items"
...         else:
...             return "return %r items" % item
... 
>>> x = TestEllipsis()
>>> print x[2]
return 2 items
>>> print x[...]
Returning all items

Of course, there is the python documentation, and language reference. But those aren't very helpful.

怕倦 2024-07-12 17:11:31

省略号在 numpy 中用于对高维数据结构进行切片。

它的目的是此时插入尽可能多的完整切片(:)以将多维切片扩展到所有维度

示例

>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)

现在,您有一个 2x2x2x2 阶的 4 维矩阵。 要选择第四维中的所有第一个元素,您可以使用省略号表示法

>>> a[..., 0].flatten()
array([ 0,  2,  4,  6,  8, 10, 12, 14])

,这相当于

>>> a[:,:,:,0].flatten()
array([ 0,  2,  4,  6,  8, 10, 12, 14])

在您自己的实现中,您可以自由地忽略上面提到的约定并将其用于您认为合适的任何内容。

The ellipsis is used in numpy to slice higher-dimensional data structures.

It's designed to mean at this point, insert as many full slices (:) to extend the multi-dimensional slice to all dimensions.

Example:

>>> from numpy import arange
>>> a = arange(16).reshape(2,2,2,2)

Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation

>>> a[..., 0].flatten()
array([ 0,  2,  4,  6,  8, 10, 12, 14])

which is equivalent to

>>> a[:,:,:,0].flatten()
array([ 0,  2,  4,  6,  8, 10, 12, 14])

In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit.

农村范ル 2024-07-12 17:11:31

这是省略号的另一个用途,它与切片无关:我经常在与队列的线程内通信中使用它,作为表示“完成”的标记; 它就在那里,它是一个对象,它是一个单例,它的名字意味着“缺乏”,而且它不是过度使用的 None (它可以作为正常数据流的一部分放入队列中)。 YMMV。

This is another use for Ellipsis, which has nothing to do with slices: I often use it in intra-thread communication with queues, as a mark that signals "Done"; it's there, it's an object, it's a singleton, and its name means "lack of", and it's not the overused None (which could be put in a queue as part of normal data flow). YMMV.

凌乱心跳 2024-07-12 17:11:31

正如其他答案中所述,它可用于创建切片。
当您不想编写许多完整切片符号 (:) 时,或者当您不确定所操作的数组的维数是多少时,这很有用。

我认为重要的是要强调的是,即使没有更多的维度需要填充,它也可以使用,而其他答案则缺少这一点。

示例:

>>> from numpy import arange
>>> a = arange(4).reshape(2,2)

这将导致错误:

>>> a[:,0,:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array

这将起作用:

a[...,0,:]
array([0, 1])

As stated in other answers, it can be used for creating slices.
Useful when you do not want to write many full slices notations (:), or when you are just not sure on what is dimensionality of the array being manipulated.

What I thought important to highlight, and that was missing on the other answers, is that it can be used even when there is no more dimensions to be filled.

Example:

>>> from numpy import arange
>>> a = arange(4).reshape(2,2)

This will result in error:

>>> a[:,0,:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array

This will work:

a[...,0,:]
array([0, 1])
执着的年纪 2024-07-12 17:11:31

与 Numpy 一起使用时,Ellipsis... 允许编写适用于一维向量和高维数组的通用函数。

例如,假设我们想要编写一个(故意简单的)函数,从数组的每一行中提取一组特定元素

def fun(arr):
    return arr[:, 1:4]

我们创建一个 2 维数组

>>> import numpy as np
>>> a = np.arange(3*5).reshape(3, 5)
>>> a

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

该函数的结果为数组 a然而

>>> fun(a)

array([[ 1,  2,  3],
       [ 6,  7,  8],
       [11, 12, 13]])

,如果我们现在创建一个一维向量 b

>>> b =  np.arange(5)
>>> b

array([0, 1, 2, 3, 4])

该函数会抛出一个错误 b 因为它只有一维 一个

>>> fun(b)

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

适用于向量和数组的通用函数可以使用 Ellipsis... Numpy 表示

def fun_ell(arr):
    return arr[..., 1:4]

法对矩阵(或高维数组)和向量按预期工作

>>> fun_ell(a)

array([[ 1,  2,  3],
       [ 6,  7,  8],
       [11, 12, 13]])

>>> fun_ell(b)

array([1, 2, 3])

此功能对于更多用途很有用复杂的函数,并在 Numpy 包中广泛使用。

When used with Numpy, the Ellipsis or ... allows one to write general functions that work for both 1-dimensional vectors and higher-dimensional arrays.

For example, suppose we want to write a (intentionally trivial) function that extracts a certain set of elements from every row of an array

def fun(arr):
    return arr[:, 1:4]

We create a 2-dim array

>>> import numpy as np
>>> a = np.arange(3*5).reshape(3, 5)
>>> a

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

The result of this function for the array a gives

>>> fun(a)

array([[ 1,  2,  3],
       [ 6,  7,  8],
       [11, 12, 13]])

However, if we now create a 1-dim vector b

>>> b =  np.arange(5)
>>> b

array([0, 1, 2, 3, 4])

The function throws an error for b because it only has one dimension

>>> fun(b)

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

A general function that works for both vectors and arrays can be written using the Ellipsis or ... Numpy notation

def fun_ell(arr):
    return arr[..., 1:4]

Which works as expected for both the matrix (or higher-dimensional arrays) and the vector

>>> fun_ell(a)

array([[ 1,  2,  3],
       [ 6,  7,  8],
       [11, 12, 13]])

>>> fun_ell(b)

array([1, 2, 3])

This functionality is useful for more complex functions and is extensively used within the Numpy package.

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