为什么python/numpy的+ =会改变原始数组? [英] Why does python/numpy's += mutate the original array?

查看:97
本文介绍了为什么python/numpy的+ =会改变原始数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import numpy as np

W = np.array([0,1,2])
W1 = W
W1 += np.array([2,3,4])
print W

W = np.array([0,1,2])
W1 = W
W1 = W1 + np.array([2,3,4])
print W

高位代码将使W发生变化,但低位代码将不会使W发生变化.为什么?

The upper code will mutate W, but the lower code will not mutate W. Why?

推荐答案

几乎对于任何类型的集合都是如此.这仅仅是由于python处理变量的方式. var1 += var2与带有集合的var1 = var1 + var2不同.我将尽我所能解释它,它肯定可以改进,因此欢迎任何编辑/批评.

This is true for almost any type of collection. This is simply due to the way python treats variables. var1 += var2 is not the same as var1 = var1 + var2 with collections. I'll explain it as far as I understand it, which can certainly be improved, so any edits/criticisms are welcomed.

print("1:")
x1 = [7]
y1 = x1
y1 += [3]
print("{} {}".format(x1, id(x1)))
print("{} {}".format(y1, id(y1)))

print("2:")
x2 = [7]
y2 = x2
y2 = y2 + [3]
print("{} {}".format(x2, id(x2)))
print("{} {}".format(y2, id(y2)))

输出:

1:
[7, 3] 40229784 # first id
[7, 3] 40229784 # same id
2:
[7]    40228744 # first id
[7, 3] 40230144 # new id

var1 = var1 + var2会创建一个具有新ID的新对象.它采用旧值,将其添加到第二个变量,然后使用第一个对象的名称将其分配给新对象.在var1 += var2示例中,它只是将其附加到ID指向的对象上,该ID与旧变量相同.

Saying var1 = var1 + var2 creates a new object with a new ID. It takes the old value, adds it to the 2nd variable, and assigns it to a new object with the NAME of the first object. In the var1 += var2 example, it simply appends it to the object pointed at by the ID, which is the same as the old variable.

这篇关于为什么python/numpy的+ =会改变原始数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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