How to read slicing with negative step

百般思念 提交于 2020-03-16 06:11:30

问题


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[:8:-1] #Ouput: [9]

Why? We give it an end of 8, and a step of -1. How come it behaves in this way?


回答1:


If you omit the first part of the slice expression, it defaults to 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. In this case, you are counting down, so :8:-1 is equivalent to slice(-1, 8, -1).



来源:https://stackoverflow.com/questions/59920270/how-to-read-slicing-with-negative-step

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!