python assignment in array vs scalar

前端 未结 1 635
醉酒成梦
醉酒成梦 2021-01-25 01:44

I have a 2D array A of shape (4,3), and a 1D array a of shape (4,). I want to swap the first two rows of A, as w

相关标签:
1条回答
  • 2021-01-25 01:49

    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.

    0 讨论(0)
提交回复
热议问题