Python 切片中的 `a[start:stop, i]` 是什么?

What is `a[start:stop, i]` in Python slicing?

Python built-in function slice 的文档是(强调我的):

class slice(stop)
class slice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by NumPy and other third party packages. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

a[start:stop, i] 是什么意思?

我试过了(在 Python 3.6 中):

a = [1, 2, 3, 4, 5, 6]
a[1:3,1]

但得到了:

TypeError: list indices must be integers or slices, not tuple

您不能将 :, 与列表结合使用。

:直接切片:

a[1:3:1]

,slice 一起使用:

a[slice(1,3,1)]

然而,借助支持它的对象(如 numpy 数组),您可以在多个维度上进行切片:

import numpy as np
a = np.array([[0,1,3],[3,4,5]])
a[0:1,2]

输出:array([3])