在 Python 中真的可以使用切片项列表吗?

Is a list of slice items really possible in Python?

根据 documentation,切片操作需要主切片和逗号分隔的切片项列表。

slicing      ::=  primary "[" slice_list "]"
slice_list   ::=  slice_item ("," slice_item)* [","]
slice_item   ::=  expression | proper_slice
proper_slice ::=  [lower_bound] ":" [upper_bound] [ ":" [stride] ]

按照我的理解,这样的表达式一定是可以的(这里,primary是一个列表):

primary[1::2, ::2]

但是,它会导致类型错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not tuple

文档中有一个进一步的“澄清”,在我看来,这使这个故事更加离奇:

If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key.

有人可以举例说明何时以及如何使用带逗号的切片列表吗?

这完全符合预期。列表不接受元组作为索引。您正在将元组 (slice(1, None, 2), slice(None, None, 2)) 传递到一个列表中,该列表拒绝了它。

这适用于 numpy 矩阵:

import numpy

a = numpy.matrix([
	[ 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] ])

print(a[1::2, 2::1])

Try it online!