理解切片符号

问题描述

这真的很简单:

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, 以便 ega[start:]等价于a[slice(start, None)]a[::-1]等价于a[slice(None, None, -1)]

虽然:基于-的符号对于简单的切片非常有帮助,但slice()对象的显式使用简化了切片的编程生成。

解决方法

我需要对 Python 的切片符号进行很好的解释(参考文献是加分项)。

对我来说,这个符号需要一点点掌握。

它看起来非常强大,但我还没有完全理解它。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...