I have a 1-D numpy array a = [1,2,3,4,5,6]
and a function that gets two inputs, starting_index
and ending_index
, and returns a[staring_index:ending_index]
.
Clearly I run into trouble when ending_index
is smaller than starting_index
. In this case, the function should start from the starting_index and traverse the vector a
in a circular way, i.e., return all the elements coming after starting_index
plus all the elements from index zero to ending_index
.
For instance, if starting_index=4
and ending_index=1
then the output should be output = [5,6,1]
. I can implement it with an if
condition but I was wondering if there is any Pythonic and concise way to do it?
Unfortunatly you cannot do this with slicing, you'll need to concatonate to two segments:
import numpy as np
a = [1, 2, 3, 4, 5, 6]
if starting_index > ending_index:
part1 = a[start_index:]
part2 = a[:end_index]
result = np.concatenate([part1, part2])
else:
result = a[start_index:end_index]
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