问题描述
在Python中,我可以通过多重影响来交换2个变量;它也适用于列表:
In Python I can exchange 2 variables by mean of multiple affectation; it works also with lists:
l1,l2=[1,2,3],[4,5,6]
l1,l2=l2,l1
print(l1,l2)
>>> [4, 5, 6] [1, 2, 3]
但是当我要交换2个numpy数组的行时(例如在高斯算法中),它将失败:
But when I want to exchange 2 rows of a numpy array (for example in the Gauss algorithm), it fails:
import numpy as np
a3=np.array([[1,2,3],[4,5,6]])
print(a3)
a3[0,:],a3[1,:]=a3[1,:],a3[0,:]
print(a3)
>>> [[1 2 3]
[4 5 6]]
[[4 5 6]
[4 5 6]]
我认为,出于一个奇怪的原因,这两列现在指向相同的值;但这不是事实,因为在前几行之后的a3[0,0]=5
会更改a3 [0,0],但不会更改a3 [1,0].
I thought that, for a strange reason, the two columns were now pointing to the same values; but it's not the case, since a3[0,0]=5
after the preceeding lines changes a3[0,0] but not a3[1,0].
我已经找到解决该问题的方法:例如a3[0,:],a3[1,:]=a3[1,:].copy(),a3[0,:].copy()
可以工作.但是谁能解释为什么用多位行进行多种影响的交换会失败吗?我的问题与Python和Numpy的基础工作有关.
I have found how to do with this problem: for example a3[0,:],a3[1,:]=a3[1,:].copy(),a3[0,:].copy()
works. But can anyone explain why exchange with multiple affectation fails with numpy rows? My questions concerns the underlying work of Python and Numpy.
推荐答案
这可以按照您希望的方式起作用:
This works the way you intend it to:
a3[[0,1]] = a3[[1,0]]
元组分配中的两个单独的分配不相互缓冲;一个接一个发生,导致覆盖您的观察
The two separate assignments in the tuple assignment are not buffered with respect to eachother; one happens after the other, leading the overwriting your observe
这篇关于Numpy中的行交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!