我试图获取矩阵反对角线的总和。使用我的代码
r=int(input("Enter no of rows:"))
c=int(input("Enter no of cols:"))
a=[]
for i in range(r):
a.append([0]*c)
print("Enter elements:")
for i in range(len(a)):
for j in range(len(a[0])):
a[i][j]=int(input())
for i in range(len(a)):
for j in range(len(a[0])):
print(a[i][j],end=" ")
print()
n=0
for i in range(len(a)):
for j in range(len(a),0,-1):
z=a[i][j]+n
print(z)
在找到超出范围即索引错误的列表索引矩阵的反对角线之和时出现错误:
File "main.py", line 17, in <module>
z=a[i][j]+n
IndexError: list index out of range
答案 0 :(得分:1)
您的代码中有几个错误:
(len-1,-1,-1)
而不是{{1} } (len,0,-1)
而没有增加z
有关错误/修复/改进,请参见嵌入式注释。
我用固定值/随机值替换了手动输入,以缩短手动输入:
n
输出:
import random
r = 5
c = 5
a = []
# add random numbers into list of list
for i in range(r):
a.append([])
for j in range(c):
a[-1].append(random.randint(1,500))
# print data formatted
# do not recalc len(a) / len(a[0]) all the time, use r and c
for i in range(r):
for j in range(c):
print("{:>5}".format(a[i][j]),end=" ")
print()
# sum anti diagonal
n=0
# this calculates the sum of _all_ values, not of the diagonal
# do not recalc len(a) / len(a[0]) all the time, use r and c
for i in range(r):
# for j in range(c,0,-1):
# range uses (inclusive,exclusive,step) limits - your c is 1 too high
# because of 0-indexing. fix using
for j in range(c-1,-1,-1):
# z=a[i][j]+n
# you need to increment n - not do stuff to z
n += a[i][j]
print(n)
要只得到对角线,您只需要对5个值求和,就可以遍历5 * 5个值。
33 69 430 218 15
149 327 44 33 279
327 57 431 57 195
307 460 268 465 170
154 325 380 79 217
5489 # sum of ALL values
并总结这些索引。
您可以遍历这些元组-或使用sum()函数内置的python。
您可以使用范围递增/递减或范围递增计数和阴性列表索引(等效):
# generating just the indexes you need
idx = list(zip(range(r),range(c-1,-1,-1)))
print(idx) # [(0, 4), (1, 3), (2, 2), (3, 1), (4, 0)]
输出:
# using a range counting down for columns
print(sum( a[row][col] for row,col in zip(range(r), range(c-1,-1,-1)) ))
# using negative list indexing and a range counting upwards
print(sum( a[row][-col-1] for row,col in zip(range(r), range(c)) ))
要填充1093 # twice
,您还可以使用列表理解:
a
Doku: