诊断功能不会将结果保存到变量中。

import numpy as np
A = np.random.rand(4,4)
d = np.diag(A)

print d
# above gives the diagonal entries of A

# let us change one entry
A[0, 0] = 0

print d
# above gives updated diagonal entries of A


为什么diag函数会以这种方式运行?

最佳答案

np.diag将视图返回到原始数组。这意味着以后对原始数组的更改将反映在视图中。 (但是,好处是操作比创建副本快得多。)

请注意,这仅是某些numpy版本中的行为。在其他情况下,将返回副本。

要“冻结”结果,可以像d = np.diag(A).copy()一样复制它

关于python - 为什么Numpy Diag函数的行为很奇怪?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28530493/

10-12 17:02
查看更多