Imagine some numpy array, e.g. x = np.linspace(1,10)
.
x[i:j]
gives me a view into x
for the range [i,j)
.
I love that I can also do x[i:-k]
which excludes the last k
elements.
However, in order to include the last element I need to do x[i:]
.
My question is this: How do I combine these two notations if I for instance need to loop over k
.
Say that I want to do this:
l = list()
for k in [5,4,3,2,1]:
l.append(x[:-k])
l.append(x[:])
What annoys me is that last line. In this simple example of course it doesn't do much of a difference, but sometimes this becomes much more annoying. What I miss is something more DRY-like.
The following snippet course does NOT yield the desired result, but represents the style of code I seek:
l = list()
for k in [5,4,3,2,1,0]:
l.append(x[:-k])
Method #1 : Using None During list slicing, giving the desired first index K and specifying 'None' as the second argument in slicing works internally as slicing all the elements from K in list till end including it.
If you to select the last element of the array, you can use index [11] , as you know that indexing in Python begins with [0] .
You can generate a slice object using the built-in function slice() . If you want to repeatedly select the items at the same position, you only need to generate the slice object once. slice(start, stop, step) is equivalent to start:stop:step . If two arguments are specified, step is set to None .
If there isn't a value after the first colon, it means to go all the way to the end of the list. This saves us time so that we don't have to manually specify len(a) as the ending index. Okay. And that -1 I snuck in at the end?
It's a bit of a pain, but since -0
is the same as 0
, there is no easy solution.
One way to do it would be:
l = list()
for k in [5,4,3,2,1,0]:
l.append(x[:-k or None])
This is because when k
is 0, -k or None
is None
, and x[:None]
will do what you want. For other values of k
, -k or None
will be -k
.
I am not sure if I like it myself though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With