数组vs标量中的python赋值 [英] python assignment in array vs scalar

查看:130
本文介绍了数组vs标量中的python赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为(4,3)的2D数组A和一个形状为(4,)的1D数组a.我想交换A的前两行以及a中的前两个元素.我做了以下事情:

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 well as the first two elements in a. I did the following:

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

显然,它适用于a,但不适用于A.现在,第二行变为第一行,但第一行保持不变.如果我执行以下操作:

Apparently, it works for a, but fails for A. Now, the second row becomes the first row, but the first row remains unchanged. If I do the following:

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

然后,它似乎起作用了.为什么第一种方法不起作用? (但适用于a)另外,A_copy = A[0,:].copy()A_copy = A[0,:]有什么区别?

Then, it seems to work. Why the first method doesn't work? (but works for a) Also, what's the difference between A_copy = A[0,:].copy() and A_copy = A[0,:]?

推荐答案

numpy切片是基础内存的视图,默认情况下它们不会创建独立的副本(这是性能/内存优化).所以:

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,:]

制作一个A[1,:]视图和一个A[0,:]视图,然后将A[0,:]的值分配为等于A[1,:]视图中的值.但是,当要分配A[1,:]时,A[0,:]的视图现在将显示复制后的数据,因此您将得到错误的结果.在这种情况下,只需将.copy添加到第二个元素就足够了:

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.

这篇关于数组vs标量中的python赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆