It's pretty simple really:
(真的很简单:)
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
There is also the step
value, which can be used with any of the above:
(还有step
值,可以与以上任何一个一起使用:)
a[start:stop:step] # start through not past stop, by step
The key point to remember is that the :stop
value represents the first value that is not in the selected slice.
(要记住的关键点是:stop
值表示不在所选切片中的第一个值。)
So, the difference between stop
and start
is the number of elements selected (if step
is 1, the default). (因此, stop
和start
之间的差异是所选元素的数量(如果step
为1,则为默认值)。)
The other feature is that start
or stop
may be a negative number, which means it counts from the end of the array instead of the beginning.
(另一个功能是start
或stop
可以是负数 ,这意味着它是从数组的末尾而不是开头开始计数。)
So: (所以:)
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
Similarly, step
may be a negative number:
(同样, 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 is kind to the programmer if there are fewer items than you ask for.
(如果项目数量少于您的要求,Python对程序员很友好。)
For example, if you ask for a[:-2]
and a
only contains one element, you get an empty list instead of an error. (例如,如果您要求a[:-2]
并且a
仅包含一个元素,则会得到一个空列表而不是错误。)
Sometimes you would prefer the error, so you have to be aware that this may happen. (有时您会更喜欢该错误,因此您必须意识到这种情况可能会发生。)
Relation to slice()
object (与slice()
对象的关系)
The slicing operator []
is actually being used in the above code with a slice()
object using the :
notation (which is only valid within []
), ie:
(在上面的代码中,实际上使用:
表示法将切片运算符[]
与slice()
对象一起使用(仅在[]
有效),即:)
a[start:stop:step]
is equivalent to:
(等效于:)
a[slice(start, stop, step)]
Slice objects also behave slightly differently depending on the number of arguments, similarly to range()
, ie both slice(stop)
and slice(start, stop[, step])
are supported.
(切片对象的行为也取决于参数的数量,与range()
略有不同,即,都支持slice(stop)
和slice(start, stop[, step])
。)
To skip specifying a given argument, one might use None
, so that eg a[start:]
is equivalent to a[slice(start, None)]
or a[::-1]
is equivalent to a[slice(None, None, -1)]
. (要跳过指定给定参数的操作,可以使用None
,例如a[start:]
等同于a[slice(start, None)]
或a[::-1]
等同于a[slice(None, None, -1)]
。)
While the :
-based notation is very helpful for simple slicing, the explicit use of slice()
objects simplifies the programmatic generation of slicing.
(尽管基于:
的符号对于简单切片非常有用,但是对slice()
对象的显式使用简化了切片的程序化生成。)