问题
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