简体   繁体   English

如何读取负步切片

[英]How to read slicing with negative step

I have already seen some questions about slicing, but haven't seen a helpful answer concerning some of them, which I can't manage to understand very well.我已经看到了一些关于切片的问题,但没有看到关于其中一些的有用答案,我无法很好地理解。 Let's say we have this list a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] And I slice it in the following way:假设我们有这个列表a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]我按以下方式对其进行切片:

a[:8:-1] #Ouput: [9]

Why?为什么? We give it an end of 8, and a step of -1.我们给它的结尾是 8,步长是 -1。 How come it behaves in this way?它怎么会这样呢?

If you omit the first part of the slice expression, it defaults to None .如果省略切片表达式的第一部分,则默认为None When it comes time for list.__getitem__ to interpret what slice(None, 8, -1) means, it uses the sign of the step size to determine if you are counting up from 0 or down from the end of the list.list.__getitem__解释slice(None, 8, -1)含义时,它使用步长的符号来确定您是从 0 开始计数还是从列表末尾向下计数。 In this case, you are counting down, so :8:-1 is equivalent to slice(-1, 8, -1) .在这种情况下,您正在倒计时,因此:8:-1等效于slice(-1, 8, -1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM