+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n.
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
Python tutorial谈到了这个问题(向下滚动一点,直到找到关于切片的部分)。
ASCII艺术图也有助于记住切片的工作方式:
列举语法允许的可能性:
当然,如果
(high-low)%stride != 0
,那么终点将略低于high-1
。如果
stride
是负数,则在倒数后顺序会有一点变化:扩展切片(带逗号和省略号)通常只用于特殊的数据结构(如NumPy);基本序列不支持它们。
很简单真的:
还有一个
step
值,可以与以上任何一个一起使用:要记住的关键点是
:stop
值表示所选切片中的第一个值而不是。因此,stop
和start
之间的区别是所选元素的数量(如果step
是1,则为默认值)。另一个特点是
start
或stop
可能是一个负的数,这意味着它从数组的末尾而不是开头开始计数。所以:类似地,
step
可能是负数:如果项目比您要求的少,Python对程序员很好。例如,如果要求
a[:-2]
,而a
只包含一个元素,则会得到一个空列表而不是一个错误。有时你更喜欢错误,所以你必须意识到这可能发生。与
的关系slice()
对象切片运算符
[]
实际上在上述代码中与使用:
符号的slice()
对象一起使用(仅在[]
内有效),即:相当于:
Slice对象的行为也略有不同,这取决于参数的数量,类似于
range()
,即支持slice(stop)
和slice(start, stop[, step])
。 要跳过指定给定参数,可以使用None
,以便例如a[start:]
等同于a[slice(start, None)]
,或者a[::-1]
等同于a[slice(None, None, -1)]
。虽然基于
:
的表示法对于简单的切片非常有用,但是slice()
对象的显式使用简化了切片的编程生成。相关问题 更多 >
编程相关推荐