#解释Python的切片法
原问题地址: http://stackoverflow.com/questions/509211/explain-pythons-slice-notation
##问题:
我需要关于Python切片明确说明(包括参考文献)。
对我来说,切片问题有点费神。它看起来非常强大,但我还没有完全搞清楚。
##回答:
Python切片很简单:
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
还有步长,它可以用在上面任何一处中:
a[start:end:step] # start through not past end, by step
要记住的关键点是::end
中的end
所表示的值表示所选定的切片之后的第一值【译者注:也就是end
的值所对应的字符,没有包括在所选定的切片之中。可以概括为“前包括,后不包括”的范围选择原则。】所以,结束和起始的区别是索引是否被乃入切片范围(如果步长是默认值1)。
另一个特点是,起始或结束可能是负数,这就意味着它是从数组的末尾开始计数,而不是起始处开始计数。所以:
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
如果实际元素少于所提交的元素个数,Python会给出温和的反馈。例如,如果你执行a[:-2]
,而a
只包含一个元素,反馈给你的就是空的列表,而不是错误列表。有时候,你更愿意得到错误提示,所以你一定要知道出现这种情况的可能性。