Why doesn't the python slice syntax wrap around from negative to positive indices?

青春壹個敷衍的年華 提交于 2021-02-08 13:55:45

问题


I noticed, given l = [1,2,3], that l[-1:] returns [3] as expected, but that l[-1:0] returns [], very much unlike what I expected. I then tried [-1:1], which I expected to return [3,1], but it also returns [].

Is there a good reason why the slice syntax does not wrap around from negative to positive indices (and the other way round)?

It seems it would be pretty useful and pretty straightforward to implement, but maybe I'm missing something.


回答1:


Slicing has a very simple definition: you go from start by jumps of step as long as you are below stop. If start or step are negative, first add the length of the array.

One time your suggestion causes irksome behaviour is:

x[10:-10]

If x[-10] is after x[10], you want the slice from x[10] to x[len(x)-10-1]. If you have wrap-around, you'll have the slice x[10:] + x[:-10], which is mostly useless.

Wrap-around behaviour is easy to emulate (eg x[m:] + x[:n]) with the current behaviour, but the current, more useful, behavior is hard to emulate with wrap-around.




回答2:


Guido van Rossum, the original inventor of Python language, has an extensive blog post about the slice syntax here:

http://python-history.blogspot.fi/2013/10/why-python-uses-0-based-indexing.html

I do not believe there is any particular reason why it doesn't work like that. Maybe the thought didn't cross Guido's mind when he was writing the initial syntax, maybe because of clarity. In any case it is too late to add such new features to Python syntax as it could break a lot of existing software.




回答3:


First you need to know that Slicing in python is from left to right So when you try [3,1] or [-1:1] result is empty ! You can suppose that every entry in list have 2 index that shows in below :for exam ple if we have a list with 4 entry this is the indexes numbers :

[0,1,2,3,4]

or

[-5,-4,-3,-1] 

for complete understanding of slicing read have a look at here :http://structure.usc.edu/numarray/node26.html



来源:https://stackoverflow.com/questions/26118263/why-doesnt-the-python-slice-syntax-wrap-around-from-negative-to-positive-indice

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