python assignment in array vs scalar

北城余情 提交于 2019-12-02 04:53:26

numpy slices are views of the underlying memory, they don't make independent copies by default (this is a performance/memory optimization). So:

A[0,:],A[1,:] = A[1,:],A[0,:]

Makes a view of A[1,:] and a view of A[0,:], then assigns the values of A[0,:] to equal what's in the view of A[1,:]. But when it gets to assigning A[1,:], A[0,:]'s view is now showing the post-copy data, so you get the incorrect result. Simply adding .copy to the second element here would be sufficient in this case:

A[0,:], A[1,:] = A[1,:], A[0,:].copy()

because the tuple on the right is always constructed completely before assignments to the left begin, so you can use the live view for the first assignment, and only need to make a copy to preserve the values for the second assignment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!