[英]Python3 slicing negative stop and negative step
Please see below statements, from 1 to 4, this all makes sense and is inline to what I know about python slicing.请看下面的陈述,从 1 到 4,这一切都是有道理的,并且符合我对 python 切片的了解。 But I can't explain the outcome of Statement no 5. Can anyone help explain the outcome of statement 5...
但我无法解释第 5 条陈述的结果。任何人都可以帮助解释第 5 条陈述的结果......
x = [1,2,3,4,5,6,7,8,9,10]
#1
print(x[::-2])
# prints [10, 8, 6, 4, 2]
#2
print(x[:-2])
# prints [1, 2, 3, 4, 5, 6, 7, 8]
#3
print(x[:-2][::-2])
# prints [8, 6, 4, 2]
#4
print(x[::-2][:-2])
# prints [10, 8, 6]
#5 (please explain this one)
print(x[:-2:-2])
#prints [10]
As you can see from example #1, when you have a negative step value but leave off the start, it works backward starting at the last.正如您从示例 #1 中看到的那样,当您有一个负步长值但没有开始时,它会从最后一个开始反向工作。 So the first value is the last one in the
list
, which is 10
at index -1
.所以第一个值是
list
中的最后一个值,即索引-1
处的10
。
The end is given as -2
, which means the second from the last.结尾为
-2
,表示倒数第二个。 But since your step is -2
, the next in the sequence would be index -3
which is past -2
.但是由于您的步骤是
-2
,因此序列中的下一个将是索引-3
,即过去的-2
。 So the sequence ends immediately.所以序列立即结束。
#5 (please explain this one)
print(x[:-2:-2])
#prints [10]
It just starts from 0 index and stop at -2(means it will go upto third term from last) then it starts incrementing by -2.它只是从 0 索引开始并在 -2 停止(意味着它将 go 到最后的第三项)然后它开始递增 -2。 Slice syntax:
切片语法:
x[start:stop:step]
So definitely 10 will be printed所以肯定会打印 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.