[Numpy-discussion] Backwards slicing including the first element
Warren Weckesser
warren.weckesser at enthought.com
Wed Mar 10 09:49:06 EST 2010
Jerome Esteve wrote:
> Dear all,
>
> Is there a way to give an integer value to j when using a[i:j:-1] so
> that the first element of the array can be included in the slice ?
>
> I would like to use some code like a[i:i-k:-1] to get a slice of
> length k.
>
> The numpy documentation seems to suggest that j=-1 should work:
>
> "Assume n is the number of elements in the dimension being sliced.
> Then, if i is not given it defaults to 0 for k > 0 and n for k < 0 .
> If j is not given it defaults to n for k > 0 and -1 for k < 0 .
> If k is not given it defaults to 1."
>
> But a[i:i-k:-1] is empty if i-k is -1. The workaround is a[i::-1][:k],
> is there something simpler ?
You could use a[i:i-(len(a)+k):-1]. This works because a[-len(a)] is
the same as a[0].
For example:
-----
In [57]: a
Out[57]: array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
In [58]: i = 3
In [59]: for k in range(5):
....: print k, a[i:i-(len(a)+k):-1]
....:
....:
0 []
1 [13]
2 [13 12]
3 [13 12 11]
4 [13 12 11 10]
-----
Warren
>
> Many thanks in advance, Jerome.
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
More information about the NumPy-Discussion
mailing list