python - 获取矩阵(列表列表)的反对角线之和时出现 IndexError

标签 python python-3.x index-error

我正在尝试获取矩阵的反对角线之和。使用我的代码

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

最佳答案

您的代码中有几个错误:

  • 你错误地使用了 range 命令,第一个索引是包含,最后一个索引不包含 - 向后移动时你需要 (len-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)

输出:

   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

要仅获得对角线,您只需对 5 个值求和,即可循环 5*5 个值。

<小时/>

您可以使用 zip() 获取正确的索引两个 range() s:

# 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)]

并对这些指标求和。

您可以循环这些元组 - 或者使用 sum() 中内置的 python功能。

您可以使用向上/向下计数的范围向上计数的范围和否定列表索引(等效):

# 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,您还可以使用列表理解:

a = [ [random.randint(1,500) for _ in range(5)] for _ in range(5)]   # automatic or
a = [ [int(input("Number: ")) for _ in range(5)] for _ in range(5)   # manual input
<小时/>

多库:

关于python - 获取矩阵(列表列表)的反对角线之和时出现 IndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55980112/

相关文章:

python子进程popen以不同用户身份执行

python-3.x - 智能测试版投资组合 : How to generate the weights based on dollar volume traded for each date

Python 可执行文件作为 Windows 服务

python - 连接 2 个 pandas 数据框不起作用

python - 无需多次迭代即可从文件中获取数据

python - 忽略Python中的IndexError(类似于列表订阅上的空合并运算符)

Python GridSearchCV 索引 xxxxx 超出大小 xxxxxx 的范围

python - __future__ 导入是如何工作的

python - python中函数的准确计时