Negative array indicies and slice()

88888 Dihedral dihedral88888 at googlemail.com
Thu Nov 1 21:08:33 EDT 2012


andrew... at gmail.com於 2012年10月29日星期一UTC+8上午11時12分11秒寫道:
> The slice operator does not give any way (I can find!) to take slices from negative to positive indexes, although the range is not empty, nor the expected indexes out of range that I am supplying.
> 
> 
> 
> Many programs that I write would require introducing variables and logical statements to correct the problem which is very lengthy and error prone unless there is a simple work around.
> 
> 
> 
> I *hate* replicating code every time I need to do this!
> 
> 
> 
> I also don't understand why slice() is not equivalent to an iterator, but can replace an integer in __getitem__() whereas xrange() can't.
> 
> 
> 
> 
> 
> Here's an example for Linux shell, otherwise remove /bin/env...
> 
> {{{#!/bin/env python
> 
> a=[1,2,3,4,5,6,7,8,9,10]
> 
> print a[-4:3]  # I am interested in getting [7,8,9,10,1,2] but I get [].
> 
> }}}
I'll suggest to use the reverse method
to get what you want.

Of course, the reverse method is not efficient for 
a list of a huge number of objects in python.




More information about the Python-list mailing list