a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array
还有一个 "step "值,它可以与上述任何一个值一起使用。
a[start:stop:step] # start through not past stop, by step
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
同样,step也可以是一个负数。
a[::-1] # all items in the array, reversed
a[1::-1] # the first two items, reversed
a[:-3:-1] # the last two items, reversed
a[-3::-1] # everything except the last two items, reversed
这其实很简单。
还有一个 "step "值,它可以与上述任何一个值一起使用。
需要记住的关键点是,
:stop
值代表*不在所选片断中的第一个值。所以,stop'和
start'的区别是所选元素的数量(如果`step'是1,默认)。另一个特点是
start
或stop
可以是一个*负数,这意味着它是从数组的末端而不是开始计算的。所以。同样,
step
也可以是一个负数。如果项目比你要求的少,Python会对程序员很友好。例如,如果你要求
a[:-2]
,而a
只包含一个元素,你会得到一个空列表而不是一个错误。有时你会更喜欢错误,所以你必须意识到这种情况可能发生。与
slice()
对象的关系切片操作符
[]
在上面的代码中实际上是与slice()
对象一起使用:
符号(只在[]
中有效), 即:相当于。
根据参数的数量,切片对象的行为也略有不同,与
range()
类似,即slice(stop)
和slice(start, stop[, step])
都支持。 要跳过指定的参数,可以使用None
,因此,例如a[start:]
等同于a[slice(start, None)]
或a[:-1]
等同于`a[slice(None, None, -1)]。虽然基于
:
的符号对简单的切片很有帮助,但明确使用slice()
对象简化了切片的程序化生成。Python 教程]1谈到了它(向下滚动一点,直到你看到关于切片的部分)。
ASCII艺术图对于记住切片的工作方式也很有帮助。
列举了语法所允许的可能性。
当然,如果
(高-低)%stride != 0
,那么终点会比高-1
低一点。如果
stride
是负数,那么排序就会有一些改变,因为我们是在倒数。扩展分片(带逗号和省略号)大多只用于特殊的数据结构(如NumPy);基本序列不支持它们。