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.

有帮助吗?

解决方案

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]

其他提示

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]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top