题目:求一个3*3矩阵主对角线元素之和。
1 # -*- coding:utf-8 -*-
2
3 l1 = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
4 for i in l1:
5 print i
6 num = 0
7 for i in range(3):
8 for j in range(3):
9 a = l1[i]
10 b = a[j]
11 print b,
12 if i == j:
13 num += b
14 print '对角线之和为%d'%num
结果为:
cl@cl-M14xR2:~/pythoncl/python练手100题$ python 47.py
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
1 1 1 2 2 2 3 3 3 对角线之和为6