3 回答

TA贡献1802条经验 获得超4个赞
你的方法确实有效:
import numpy as np
b = [1,2,3,4,5,6,7,8,9]
a = np.zeros((9, 9), int)
np.fill_diagonal(a, b)
替代:
a[np.diag_indices_from(a)] = b

TA贡献1810条经验 获得超4个赞
只是为了好玩,np.eye有广播。
np.eye(a.shape[0], dtype=int) * b
array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 4, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 5, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 6, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 7, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 9]])
您也可以使用diagflat, 如果b的尺寸 > 1D
np.diagflat(b)
# np.diagflat([b])
# np.diagflat(np.array([b]))
array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 4, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 5, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 6, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 7, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 9]])
添加回答
举报