python切片不容错过的一篇文章

2018-09-10  本文已影响0人  少寨主的互联网洞察

题目

我需要对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

还有步长(step)值,可用于上述任何一项:

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

需要记住的关键是:end值表示在选定的片中第一个没有的值。因此,end和start之间的插值表示所选元素的数量(如果步长为1,表示默认)。

另一个特性是start或end可能是一个负数,这意味着它从数组的末尾而不是开始计数。所以:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

同样,步长可能是负数:

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只包含一个元素,那么您将得到一个空列表而不是一个错误。有时你更喜欢错误,所以你必须意识到这可能发生。

上一篇 下一篇

猜你喜欢

热点阅读