[英]Understanding pythons reverse slice ( [::-1] )
I always thought that omitting arguments in the python slice operation would result into: 我一直认为忽略python slice操作中的参数会导致:
0
开始= 0
len(lst)
结束= len(lst)
1
步= 1
That holds true if the step is positive, but as soon as the step is negative, like in the "reverse slice" [::-1]
, omitting start/end results in: 如果步长为正,则成立,但步长为负时,如“ reverse slice” [::-1]
,省略开始/结束将导致:
len(lst)-1
开始= len(lst)-1
None
结束= None
Is this a special case, or am I missing something? 这是特例,还是我错过了什么?
The default is always None
; 默认值始终为 None
; it is up to the type to determine how to handle None
for any of the 3 values. 由类型决定如何None
三个值中的任何一个处理None
。 The list
object is simply passed a slice(None, None, -1)
object in this case. 在这种情况下slice(None, None, -1)
只将list
对象传递给slice(None, None, -1)
对象。
See footnote 5 to the operations table in the sequence types documentation for how Python's default sequence types (including list objects) interpret these: 有关Python的默认序列类型(包括列表对象)如何解释这些信息,请参见序列类型文档中操作表的脚注5:
s[i:j:k]
5. [...] If i or j are omitted orNone
, they become “end” values (which end depends on the sign of k ). 5. [...]如果省略i或j或None
,它们将成为“结束”值(该结束取决于k的符号)。
So the defaults are dependent on the sign of the step value; 因此,默认值取决于步长值的符号。 if negative the ends are reversed. 如果为负,则两端颠倒。 For [::-1]
the end values are len(s) - 1
and -1
(absolute, not relative to the end), respectively, because the step is negative. 对于[::-1]
,最终值分别为len(s) - 1
和-1
(绝对值,不是相对于最终值),因为步长为负数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.