Python Numpy 中的行交换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21288044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Row exchange in Numpy
提问by JPG
In Python I can exchange 2 variables by mean of multiple affectation; it works also with lists:
在 Python 中,我可以通过多重影响来交换 2 个变量;它也适用于列表:
l1,l2=[1,2,3],[4,5,6]
l1,l2=l2,l1
print(l1,l2)
>>> [4, 5, 6] [1, 2, 3]
But when I want to exchange 2 rows of a numpy array (for example in the Gauss algorithm), it fails:
但是当我想交换 numpy 数组的 2 行时(例如在高斯算法中),它失败了:
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]]
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]=5after the preceeding lines changes a3[0,0] but not a3[1,0].
我认为,出于一个奇怪的原因,这两列现在指向相同的值;但事实并非如此,因为a3[0,0]=5在前面的行更改 a3[0,0] 而不是 a3[1,0] 之后。
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.
我已经找到了如何处理这个问题:例如a3[0,:],a3[1,:]=a3[1,:].copy(),a3[0,:].copy()有效。但是谁能解释为什么用 numpy 行进行多重伪装的交流会失败?我的问题涉及 Python 和 Numpy 的底层工作。
回答by Eelco Hoogendoorn
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
元组分配中的两个单独分配没有相互缓冲;一个接一个发生,导致覆盖你的观察

