NumPy数组切片[::-1]的作用及相关疑问解析
[::-1] and .. Let's break down your questions one by one with clear examples, including the code snippet you shared.
What does [::-1] do for NumPy arrays?
The slice [::-1] is a shorthand for reversing the order of elements along a specific dimension. NumPy slicing follows the format [start:stop:step]:
- When
startandstopare omitted, they default to the full range of the dimension (from the first to last element). - The
step=-1tells NumPy to traverse the dimension in reverse order, picking every element from the end to the start.
What does A[::-1] do specifically (using your example)?
Your array x is a 3-dimensional array with shape (2, 3, 3):
import numpy as np x = np.indices((3,3)) # x[0] = [[0,0,0], [1,1,1], [2,2,2]] (first element of axis 0) # x[1] = [[0,1,2], [0,1,2], [0,1,2]] (second element of axis 0)
When you run x[::-1], you're reversing the first dimension (axis=0) of the array. This swaps the order of the two top-level elements in x:
- The first element of the result is
x[1](the original second element) - The second element of the result is
x[0](the original first element)
Which matches your output:
array([[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 0, 0], [1, 1, 1], [2, 2, 2]]])
Does the -1 refer to any column dimension?
No, the -1 here is not tied to a column dimension—it's the step value for the slice. Columns in your example are the third dimension (axis=2). If you wanted to reverse columns, you'd need to target that specific axis, like x[:,:,::-1] (reverses the last dimension). For example:
x[:,:,::-1] # Output would have each row's columns reversed, e.g., [0,1,2] becomes [2,1,0]
What does the double dot (..) mean in slicing?
The .. (ellipsis) is a convenient shorthand for omitting all unspecified middle dimensions. It acts as a replacement for multiple : slices, making code cleaner when working with high-dimensional arrays.
- For your 3D array
x,x[..,::-1]is exactly equivalent tox[:,:,::-1](reverses the last dimension, columns). - For a 4D array
ywith shape(2,3,4,5),y[1,..,3]would be the same asy[1,:,:,3]—selecting the second element of axis 0, all elements of axes 1 and 2, and the fourth element of axis 3.
内容的提问来源于stack exchange,提问作者ling

