38求一个3*3矩阵主对角线元素之和
程序分析:利用双重for循环控制输入二维数组,再将a[i][i]累加后输出。
输入矩阵的方法
1#直接计算已知矩阵的主对角线元素之和
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
#输出矩阵
for row in matrix:
print(row)
sum = 0
for i in range(3):
sum += matrix[i][i]
print(sum) #和for对齐直接输出结果
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
1
6
15
2#求任意3*3主对角线元素之和
if __name__ == "__main__":
a = []
sum = 0.0
for i in range(3):
a.append([])
for j in range(3):
a[i].append(float(input("input num:\n"))) #输入每3个为一行
print(a)
for i in range(3):
sum += a[i][i]
print(sum)
input num:
1
input num:
1
input num:
1
input num:
2
input num:
2
input num:
2
input num:
3
input num:
3
input num:
3
[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]
6.0
3 直接输入矩阵(python里矩阵每一行是一个列表)
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
#输出矩阵
print(matrix)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
4 import numpy as np输入矩阵
import numpy as np
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(matrix)
[[1 2 3]
[4 5 6]
[7 8 9]]