sna*_*ubo 5 python slice python-3.x
以下是我从The Python Language Reference中复制的切片语法:
slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression
Run Code Online (Sandbox Code Playgroud)
根据我的理解,这种语法相当于SomeMappingObj[slice_item,slice_item etc...]再次等同于a[0:2:1,4:7:1]和a =[i for i in range(20)].
但是,我无法在IPython中测试这个,我没有发现任何关于多个切片的问题.我对python中多次切片的解释是否正确?我做错了什么?
In [442]: a=[i for i in range(20)]
In [443]: a[0:12:2]
Out[443]: [0, 2, 4, 6, 8, 10]
In [444]: a[0:12:2,14:17:1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-444-117395d33bfd> in <module>()
----> 1 a[0:12:2,14:17:1]
TypeError: list indices must be integers or slices, not tuple
Run Code Online (Sandbox Code Playgroud)
Aslice_list应该包含与被索引的对象一样多的“维度”。据我所知,任何 Python 库对象都没有使用多维功能,但您可以使用以下方法轻松测试它numpy:
import numpy as np
a = np.array([[1, 2], [3, 4]])
a[0:1, 0]
Run Code Online (Sandbox Code Playgroud)
Python 语言中有许多此类功能并未在主库中直接使用。魔术__matmul__方法(@运算符)是另一个例子。