gpt4 book ai didi

Python矩阵添加对角线元素

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:01 26 4
gpt4 key购买 nike

我需要制作一个小程序,它将采用 4x4 矩阵并添加列和行的对角线。

1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

像这样会加 1+2+3+4。

抱歉含糊不清,这就是我想出的方法,可以通过每列直接向下添加一个矩阵。我还没有使用过 numpy。

matrix = [1,2,3,4],[5,6,7,8],[9,10,11,12] #Assume a list is given
total = 0
for column in range(0, len(matrix[0])):
for row in range(0, len(matrix)):
total += matrix[row][column]
print("Sum for column " + str(column) + " is " + str(total))
total = 0 #Reset total to zero before restarting count

我不是 100% 从哪里开始,所以任何想法都会很棒。我的老师告诉我们抵消作为提示。

最佳答案

对角线元素在同一行列坐标:

matrix = [[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4]]
answer = sum(matrix[i][i] for i in range(len(matrix)))

关于Python矩阵添加对角线元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34997387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com