试图在#6创建的列表的#7中对角地获得总和.所以说清单是[[2,3,1],[1,1,1],[5,6,4]],总和是2 1 4
#6
def randomlists(s):
b=s
list1 = []
while s>0:
sublist = []
for x in range(0,b):
sublist.append(randrange(-100,101))
list1.append(sublist)
s-=1
return list1
#print(randomlists(5))
#7
def diagonalsum(x):
a=randomlists(x)
count=0
print (a)
for b in a:
while count<x:
d=a[0]
b=a[1]
c=a[2]
print (a[(count)])
count+=1
return d+b+c
print (diagonalsum(3))
解决方法:
假设矩阵是方形的,这是使用循环的标准解决方案:
def diagonalsum(m):
count = 0
for i in xrange(0, len(m)):
count += m[i][i]
return count
…通过使用生成器表达式和求和函数,可以更简洁的方式编写:
def diagonalsum(m):
return sum(m[i][i] for i in xrange(len(m)))