问题描述
我正在用python切片列表,无法解释某些结果.以下两个对我来说似乎很自然:
I'm slicing lists in python and can't explain some results.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]
但是
>>>[0,1,2,3,4,5][1:4:-1]
[]
以为我希望它是[3,2,1].为什么会产生[]?为什么不反转列表?首先在python,步骤或切片内部发生什么?
thought I expected it to be [3,2,1]. Why does it produce [ ]? Why does it not reverse the list? What happens first inside python, the step or the slicing?
我也发现
>>>[0,1,2,3,4,5][-3:-6:-1]
[3,2,1]
推荐答案
如果要对此切片,则切片将类似于此[start:end:step]
.为此:
If you are slicing this then slicing will look like this [start:end:step]
. For this one:
>>> [0,1,2,3,4,5][1:4:1]
[1, 2, 3]
它从索引1到索引3凝视着,因为它一次淘汰了索引4一步.在第二个列表中您将获得一个空列表,因为您是从第一个索引开始以-1步进.因此,这将是解决方案.
It is staring from index 1 to index 3 because it exlcudes the index 4 with 1 step at a time.You are getting an empty list in the second one because you are stepping -1 from 1st index. So this will be the solution.
>>> [0,1,2,3,4,5][4:1:-1]
[4, 3, 2]
之所以起作用,是因为您将索引从4向前索引为-1,而前进了-1.
This works because you are taking an index from 4 to one with -1 step forward.
这篇关于为什么扩展切片不能反转列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!