数组中的减法会影响结果

Subtraction in array affects the result

当我将一个矩阵的数组保存到另一个变量中时,当我改变矩阵的值时,另一个变量的值也被改变了。不知道为什么。

import numpy as np

a = np.array([[1,2,3],[4,5,6]])
b = a[1,:]
print a
print b

a[1,:] = a[1,:] - a[0,:]
print a
print b

结果是

[[1 2 3]
 [4 5 6]]
[4 5 6]

[[1 2 3]
[3 3 3]]
[3 3 3]

在这个脚本中,当a改变时b的值也改变了。

您需要阅读更多关于浅拷贝的内容:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations.

  • The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

示例:

>>> lst1 = ['a','b',['ab','ba']]
>>> lst2 = lst1[:]
>>> lst2[0] = 'c'
>>> lst2[2][1] = 'd'
>>> print(lst1)
['c', 'b', ['ab', 'd']]

现在,您必须使用deepcopy,例如:

>>>from copy import deepcopy
>>>lst1 = ['a','b',['ab','ba']]
>>>lst2 = deepcopy(lst1)
>>>lst2[2][1] = "d"
>>>lst2[0] = "c";
>>>print lst2
>>>print lst1
['c', 'b', ['ab', 'd']]
['a', 'b', ['ab', 'ba']]

您可以阅读有关 Shallow and Deep Copy 的更多信息。