本文介绍了如何在python中找到矩阵对角线上方和下方的元素总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到主对角线上方和下方的元素的总和.我不知道如何调整算法的总和.这是我到目前为止的代码,其中A是矩阵

I need to find the sum of the elements that are above and below the main diagonal. I have no idea how to condition the algorithm to sum only those numbers. This is the code I have so far, with A being the matrix

A = []
N = int(raw_input("Input matrix size: "))
for i in range(0, N):
    row = []
    for j in range(0, N):
        row.append(int(raw_input("Input elements: ")))
    A.append(row)
sum = 0
for i in range(0, N):
    sum += A[i][i]
print sum
sum2 = 0
for i in range(0, N):
    for j in range(i+1, N):
        sum2 += A[i][j]
print sum2

我猜我应该为语句使用更多.谢谢

I am guessing I should use more for statements.Thank you

推荐答案

您可以使用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

这篇关于如何在python中找到矩阵对角线上方和下方的元素总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 15:31