了解切片
我需要一个关于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
要记住的关键点是,该值表示不在所选切片中的第一个值。因此,和 之间的差值是所选元素的数量(如果为 1,则为默认值)。:stop
stop
start
step
另一个特征是 或 可能是负数,这意味着它从数组的末尾而不是开头开始计数。所以: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
切片
对象可以表示切片操作,即:
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)]
虽然基于 -based 的表示法对于简单切片非常有用,但对象的显式使用简化了切片的编程生成。:
slice()
Python教程讨论了它(向下滚动一下,直到你到达关于切片的部分)。
ASCII 艺术图对于记住切片的工作原理也很有帮助:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
记住切片工作原理的一种方法是将索引视为指向字符之间的索引,第一个字符的左边缘编号为 0。则 n 个字符字符串的最后一个字符的右边缘具有索引 n。