简体   繁体   English

为什么会这样? (关于矩阵行的交换)

[英]Why does this happen? (about the exchange of rows of matrix)

It is given that鉴于

A = np.array([[1, 2, 3],
       [4, 5, 6],
       [6, 5, 4],
       [3, 2, 1]])

and I want to exchange the second row and the third row.我想交换第二排和第三排。 It doesn't matter how I should write the code, but I found something so strange.我应该如何编写代码并不重要,但我发现了一些很奇怪的东西。

Case 1:情况1:

B = A
A[1,:] = B[2,:]
A[2,:] = B[1,:]

Case 2:案例二:

B = []
B.append(A[1,:])
B.append(A[2,:])
A[2,:] = B[0]
A[1,:] = B[1]

Neither the case cannot realize what I want, since B is always changed even if just changing A .这两种情况都无法实现我想要的,因为即使只是改变A也总是会改变B Why does it happen?为什么会这样? In another different case but with a similar spirit, that is, given a=2 and b=1 , if we run在另一个不同的情况下,但具有相似的精神,即给定a=2b=1 ,如果我们运行

c = b
b = a
a = c

then the exchange will work well?那么交易所会运作良好吗? Why?为什么?

Arrays are called by reference, atomic variables are called by value. Arrays 通过引用调用,原子变量通过值调用。 Meaning, in the last example, c gets the value of b , but in the first case A and B are actually pointing to the same array, so your second line overwrites A .意思是,在最后一个示例中, c获取b,但在第一种情况下AB实际上指向同一个数组,因此您的第二行将覆盖A So, if you did B=np.copy(A) , all would be well.所以,如果你做了B=np.copy(A) ,一切都会好起来的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM