[英]Why does extended slicing not reverse the list?
I'm slicing lists in python and can't explain some results. 我在python中切片列表,无法解释一些结果。 Both of the following seem natural to me: 以下两个对我来说似乎很自然:
>>>[0,1,2,3,4,5][1:4:1]
[1, 2, 3]
>>>[0,1,2,3,4,5]
[::-1] == [5,4,3,2,1,0]
However, 然而,
>>>[0,1,2,3,4,5][1:4:-1]
[]
thought I expected it to be [3,2,1]. 以为我期望它是[3,2,1]。 Why does it produce [ ]? 为什么会产生[]? Why does it not reverse the list? 为什么不反转列表? What happens first inside python, the step or the slicing? 首先在python,步骤或切片内部发生什么?
I also found that 我也发现
>>>[0,1,2,3,4,5][-3:-6:-1]
[3,2,1]
The third number in the slice is the step count. 切片中的第三个数字是步数。 So, in [0,1,2,3,4,5][1:4:-1]
, the slicing starts at 1
and goes DOWN by 1
until it is less than 4
, which is immediately is. 因此,在[0,1,2,3,4,5][1:4:-1]
,切片从1
开始,然后向下DOWN 1
直到小于4
为止。 Try doing this: 尝试这样做:
>>> [0,1,2,3,4,5][4:1:-1]
[4, 3, 2]
If you are slicing this then slicing will look like this [start:end:step]
. 如果要切片,则切片将如下所示[start:end:step]
。 For this one: 为此:
>>> [0,1,2,3,4,5][1:4:1]
[1, 2, 3]
It is staring from index 1 to index 3 because it exlcudes the index 4 with 1 step at a time. 它从索引1到索引3凝视着,因为它一次以1步就排除了索引4。 You are getting an empty list in the second one because you are stepping -1 from 1st index. 在第二个列表中您将获得一个空列表,因为您是从第一个索引中移出-1。 So this will be the solution. 因此,这将是解决方案。
>>> [0,1,2,3,4,5][4:1:-1]
[4, 3, 2]
This works because you are taking an index from 4 to one with -1 step forward. 之所以可行,是因为您将索引从4向前扩展为-1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.