与numpy操作a [:]和a [...]混淆 [英] get confused with numpy operation a[:] and a[...]
问题描述
在numpy中,存在一些切片操作,例如a [1:3,3:5],但是我对操作a [:]和a [...]感到困惑,我是python的新手,可以有人解释这两者之间有什么区别吗?
In numpy, there exists some slicing operation like a[1:3,3:5], however I am confused with the operation a[:] and a[...],I am a novice at python, can anyone explain what's the difference between these?
推荐答案
...
是省略号,在纯Python中,它基本上是一个非运算符.在这种情况下,它用作代码的占位符:
The ...
is the Ellipsis, in pure Python it's basically a none-operator. It serves as a placeholder for code such as in this case:
while True:
...
在numpy中,它具有类似的用途,它是请勿切"运算符.由于numpy同时支持多个切片,因此这很有用.例如,要获取多维数据集的不同边,
Within numpy it serves a similar purpose, it's the do-not-slice operator. Since numpy supports multiple slices at the same time this can be useful. For example, to get the different edges of a cube:
In [1]: import numpy
In [2]: cube = numpy.arange(3**3).reshape(3, 3, 3)
In [3]: cube
Out[3]:
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
In [4]: cube[0, ..., 0]
Out[4]: array([0, 3, 6])
In [5]: cube[..., 0, 0]
Out[5]: array([ 0, 9, 18])
In [6]: cube[0, 0, ...]
Out[6]: array([0, 1, 2])
应注意,在上述情况下,...
在功能上与:
相同,但对于多维对象它可能有所不同:
It should be noted that ...
is functionally identical to :
in the cases above, but it can be different for multi-dimensional objects:
In [7]: cube[..., 0]
Out[7]:
array([[ 0, 3, 6],
[ 9, 12, 15],
[18, 21, 24]])
In [8]: cube[:, 0]
Out[8]:
array([[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20]])
在多维对象中,...
根据需要插入:
多次,以达到完整尺寸
In multi-dimensional objects the ...
inserts the :
as many times as needed to reach a full dimension
这篇关于与numpy操作a [:]和a [...]混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!