Dan
Dan

Reputation: 12675

Getting a reversed slice of an array that includes the base element

I'm using numpy arrays. I'm trying to calculate an array that contains the products of elements spreading out from some center. My code curently looks like this, where psi is a numpy.array():

up=psi[position:position+width]
pre_down=psi[position-width+1:position+1]
down=pre_down[::-1]
ac=up*down

Is there a more elegant, pythonic way to make the array "down"? Something like

down=psi[position:position-width:-1]

doesn't work when position-width is 0.

Upvotes: 1

Views: 55

Answers (2)

Ben
Ben

Reputation: 2472

You can use the or keyword to replace the value 0 with None, giving you the base element.

down=psi[position:position-width or None:-1]

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308364

When you need to slice down to element 0, you can use None for the end of the slice.

end = position - width - 1 if position > width else None
down = psi[position:end:-1]

Upvotes: 3

Related Questions