Extended slice that goes to beginning of sequence

2019-02-04 14:47发布

Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.

In python, you can index lists using slice notation. Here's an example:

>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]

You can also include a stride, which acts like a "step":

>>> A[0:5:2]
[0, 2, 4]

The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:

>>> A[5:0:-1]
[5, 4, 3, 2, 1]

But wait! I wanted to see [4, 3, 2, 1, 0]. Oh, I see, I need to decrement the start and end indices:

>>> A[4:-1:-1]
[]

What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:

>>> A[4::-1]
[4, 3, 2, 1, 0]

But you can't use this in all cases. For example, in a method that's been passed indices.

My question is:

Is there any good pythonic way of using extended slices with negative strides and explicit start and end indices that include the first element of a sequence?

This is what I've come up with so far, but it seems unsatisfying.

>>> A[0:5][::-1]
[4, 3, 2, 1, 0]

9条回答
聊天终结者
2楼-- · 2019-02-04 15:40
a[4::-1]

Example:

Python 2.6 (r26:66714, Dec  4 2008, 11:34:15) 
[GCC 4.0.1 (Apple Inc. build 5488)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[4:0:-1]
[4, 3, 2, 1]
>>> a[4::-1]
[4, 3, 2, 1, 0]
>>> 

The reason is that the second term is interpreted as "while not index ==". Leaving it out is "while index in range".

查看更多
Fickle 薄情
3楼-- · 2019-02-04 15:42
[ A[b] for b in range(end,start,stride) ]

Slower, however you can use negative indices, so this should work:

[ A[b] for b in range(9, -1, -1) ]

I realize this isn't using slices, but thought I'd offer the solution anyway if using slices specifically for getting the result isn't a priority.

查看更多
ら.Afraid
4楼-- · 2019-02-04 15:45

I know this is an old question, but in case someone like me is looking for answers:

>>> A[5-1::-1]
[4, 3, 2, 1, 0]

>>> A[4:1:-1]
[4, 3, 2]
查看更多
登录 后发表回答