Python 中的切片

95 阅读2分钟

Python 中语法的切片为:

a[start:stop]  # items start through stop-1 从start到stop-1的元素
a[start:]      # items start through the rest of the array 从start到结尾的元素
a[:stop]       # items from the beginning through stop-1 从开始到stop-1的元素
a[:]           # a copy of the whole array 复制整个数组

还有一个step参数可以用在上面:

a[start:stop:step] # start through not past stop, by step

另外一点就是startstop可以是负数,这样的话它就是从尾部向头部计算的:

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  翻转的除了最后两个元素的其他元素

如果数组中的元素要比你请求的元素还要少,这也是没有问题的(不会报错)。比如:如果你执行a[:-2]请求a中最后两个元素,但是a本身只有一个元素,你就会只得到一个空列表而不是报错。如果你更喜欢报错的话,那就要意识到这种情况的发生。

slice()函数的关系

slice()函数和在[]中使用:是一样的:

a[start:stop:step]

等同于:

a[slice(start, stop, step)]

根据参数数量的不同,slice对象的行为也有略有不同,就像range()一样,slice(stop)slice(start, stop[, step])都是可以的。可以使用None跳过指定的参数,比如:a[start:]等同于a[slice(start, None)]a[::-1]等同于a[slice(None, None, -1)

虽然基于 : 的符号对于简单的切片非常有用,但显式使用 slice() 对象可以简化切片的生成。