You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NumPy数组切片[::-1]的作用及相关疑问解析

Understanding NumPy Slicing: [::-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 start and stop are omitted, they default to the full range of the dimension (from the first to last element).
  • The step=-1 tells 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 to x[:,:,::-1] (reverses the last dimension, columns).
  • For a 4D array y with shape (2,3,4,5), y[1,..,3] would be the same as y[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:53:16