我需要一个关于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
,因此,例如a[start:]
等同于a[slice(start, None)]
或a[:-1]
等同于`a[slice(None, None, -1)]。
虽然基于:
的符号对简单的切片很有帮助,但明确使用slice()
对象简化了切片的程序化生成。
Python 教程]1谈到了它(向下滚动一点,直到你看到关于切片的部分)。
ASCII艺术图对于记住切片的工作方式也很有帮助。
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
记住切片工作原理的一个方法是,把指数看作是指向个字符之间的,第一个字符的左边缘编号为0,那么一串n字符的最后一个字符的右边缘的指数为n*。
列举了语法所允许的可能性。
>>> seq[:] # [seq[0], seq[1], ..., seq[-1] ]
>>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ]
>>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]]
>>> seq[low:high] # [seq[low], seq[low+1], ..., seq[high-1]]
>>> seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ]
>>> seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ]
>>> seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]]
>>> seq[low:high:stride] # [seq[low], seq[low+stride], ..., seq[high-1]]
当然,如果(高-低)%stride != 0
,那么终点会比高-1
低一点。
如果stride
是负数,那么排序就会有一些改变,因为我们是在倒数。
>>> seq[::-stride] # [seq[-1], seq[-1-stride], ..., seq[0] ]
>>> seq[high::-stride] # [seq[high], seq[high-stride], ..., seq[0] ]
>>> seq[:low:-stride] # [seq[-1], seq[-1-stride], ..., seq[low+1]]
>>> seq[high:low:-stride] # [seq[high], seq[high-stride], ..., seq[low+1]]
扩展分片(带逗号和省略号)大多只用于特殊的数据结构(如NumPy);基本序列不支持它们。
>>> class slicee:
... def __getitem__(self, item):
... return repr(item)
...
>>> slicee()[0, 1:2, ::5, ...]
'(0, slice(1, 2, None), slice(None, None, 5), Ellipsis)'