用Python减去两个列数组

我有这段代码,我想在Python中减去两个2x1矩阵,但输出错误。

我希望答案是

[[-1.0]
 [1.0]
 [-1.0]]

但是我得到

[[0.]
 [0.]
 [0.]].

这是我正在使用的代码:

test = np.zeros((3,1))
test[0] = 1.0
test[1] = 2.0
test[2] = 3.0


test1 = test
test1[0] = 2.0
test1[1] = 1.0
test1[2] = 4.0

ans = test - test1
print(ans)
ajiaolong 回答:用Python减去两个列数组

您只是错误地初始化了test1

请参见下面test1 = np.zeroes((3,1))的更改

import numpy as np

test = np.zeros((3,1))
test[0] = 1.0
test[1] = 2.0
test[2] = 3.0


test1 = np.zeros((3,1))
test1[0] = 2.0
test1[1] = 1.0
test1[2] = 4.0

ans = test - test1
print(ans)

收益:

[[-1.]
 [ 1.]
 [-1.]]
,

如评论中所述,您的test1变量实际上是在引用test

因此,基本上,您是在与向量本身相减,这显然会导致向量为空。

您可以自己验证:

test1 = test
print(test1 is test)  # prints True

要避免这种行为,您需要创建其他对象,例如使用copy或切片。

test1 = test.copy()
print(test1 is test)  # prints False

test1 = test1[:]
print(test1 is test)  # prints False

这样,您可以初始化新变量并在减去矢量后获得预期结果。

test1[0] = 2.0
test1[1] = 1.0
test1[2] = 4.0

ans = test - test1
print(ans)

# prints [[-1.]
#         [ 1.]
#         [-1.]] 
本文链接:https://www.f2er.com/2973040.html

大家都在问