小编典典

Understanding slicing

python

我需要一个关于 Python 切片的很好的解释(参考是​​一个加号)。


阅读 200

收藏
2022-06-28

共1个答案

小编典典

语法是:

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()对象的显式使用简化了切片的编程生成。

2022-06-28