简体   繁体   English

不一致的 Numpy 数组别名行为

[英]Inconsistent Numpy array aliasing behavior

The following behavior is expected and is what I get.以下行为是预期的,也是我得到的。 This is consistent with how aliasing works for native Python objects like lists.这与别名对原生 Python 对象(如列表)的工作方式一致。

>>> x = np.array([1, 2, 3])
>>> y = x
>>> x
array([1, 2, 3])
>>> y
array([1, 2, 3])
>>> x = x + np.array([2, 3, 4])
>>> x
array([3, 5, 7])
>>> y
array([1, 2, 3])

But the following behavior is unexpected by changing x = x + np.array([2, 3, 4]) to x += np.array([2, 3, 4])但是,通过将x = x + np.array([2, 3, 4])更改为x += np.array([2, 3, 4])以下行为是意外的

>>> x += np.array([2, 3, 4])
>>> x
array([3, 5, 7])
>>> y
array([3, 5, 7])

The Numpy version is 1.16.4 on my machine. Numpy 版本在我的机器上是 1.16.4。 Is this a bug or feature?这是错误还是功能? If it is a feature how x = x + np.array([2, 3, 4]) differs from x += np.array([2, 3, 4])如果它是一个特征x = x + np.array([2, 3, 4])x += np.array([2, 3, 4]) , 4]) 有何不同

Your line y = x doesn't create a copy of the array;您的行y = x不会创建数组的副本; it simply tells y to point to the same data as x , which you can see if you look at their id s:它只是告诉y指向与x相同的数据,如果您查看它们的id就可以看到:

x = np.array([1,2,3])
y = x
print(id(x), id(y))

(140644627505280, 140644627505280)

x = x + np.array([2, 3, 4]) will do a reassignment of x to a new id , while x += np.array([2, 3, 4]) will modify it in place. x = x + np.array([2, 3, 4])会将 x 重新分配给新的id ,而x += np.array([2, 3, 4])会将其修改到位。 Thus, the += will also modify y, while x = x +... won't.因此, +=也会修改 y,而x = x +...不会。

x += np.array([2, 3, 4])
print(id(x))
print(x, y)

x = x + np.array([2, 3, 4])
print(id(x))
print(x, y)

140644627505280
[3 5 7] [3 5 7]
140644627175744
[ 5  8 11] [3 5 7]

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

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