Understanding slicing
我需要一个关于 Python 切片的很好的解释(参考是​​一个加号)。
-
语法是:
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
要记住的关键点是该
:stop
值表示不在所选切片中的第一个值。stop
因此,和之间的差异start
是所选元素的数量(如果step
是 1,则默认值)。另一个特点是
start
或者stop
可能是一个负数,这意味着它从数组的末尾而不是开头开始计数。所以: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
对象的关系一个
slice
对象可以表示一个切片操作,即:a[start:stop:step]
相当于:
a[slice(start, stop, step)]
根据参数的数量,切片对象的行为也略有不同,类似于
range()
,即同时支持slice(stop)
和slice(start, stop[, step])
。要跳过指定给定参数,可以使用None
, 以便 ega[start:]
等价于a[slice(start, None)]
或a[::-1]
等价于a[slice(None, None, -1)]
。虽然
:
基于 - 的符号对于简单的切片非常有帮助,但slice()
对象的显式使用简化了切片的编程生成。