且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中找到矩阵对角线上方和下方的元素总和?

更新时间:2023-11-22 23:50:46

您可以使用np.triunp.trilnp.trace计算这些总和(您的问题未指定是否允许您使用numpy):

You can use np.triu, np.tril and np.trace to compute these sums (your question does not specify whether or not you are allowed to leverage numpy):

import numpy as np

np.random.seed(0)
A = np.random.randint(0,10,size=(5,5))

赠予:

[[5 0 3 3 7]
 [9 3 5 2 4]
 [7 6 8 8 1]
 [6 7 7 8 1]
 [5 9 8 9 4]]

然后:

upper_sum = np.triu(A).sum()-np.trace(A)
lower_sum = np.tril(A).sum()-np.trace(A)

收益:

34
73