其实很简单:
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
也可以与上述任何值一起使用:
a[start:stop:step] # start through not past stop, by step
要记住的关键一点是,:stop
表示选定切片中的第一个值,即not.因此,stop
和start
之间的差异是所选元素的数量(如果step
为1,则为默认值).
另一个特点是,start
或stop
可以是一个negative数字,这意味着它从数组的末尾而不是开头开始计数.因此:
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
如果项目比您要求的少,Python对程序员很友好.例如,如果您请求a[:-2]
,而a
只包含一个元素,则会得到一个空列表,而不是错误.有时您更喜欢错误,因此您必须意识到这种情况可能会发生.
slice()
object切片运算符[]
实际上在上面的代码中与使用:
表示法的slice()
对象一起使用(其仅在[]
内有效),即:
a[start:stop:step]
相当于:
a[slice(start, stop, step)]
根据参数的数量,切片对象的行为也略有不同,类似于range()
,即slice(stop)
和slice(start, stop[, step])
都受支持.
虽然基于:
的表示法对简单切片非常有帮助,但显式使用slice()
对象简化了切片的编程生成.