【发布时间】:2019-02-14 12:51:29
【问题描述】:
以下代码用于在数组中获取一组学生的分数行,并且需要找到分数最高的行。
下面是不完整的代码,因为还需要搜索最大和行;但由于错误而卡在不完整的代码中。
它在py3.codeskulptor.org/ 中给出以下错误,而在Pythontutor 中,程序在相同的行号处终止。
第 17 行:IndexError:列表分配索引超出范围
# Input number of tests
t = int(input("Input number of tests"))
# Input size of rows (of students)
n = int(input("Input size of rows"))#.strip().split())
print (t,n)
arr = [[[] for i in range(t)] for i in range(n)]
total = [[] for i in range (n)]
for i in range(0,t):
# Input score of each student in row
sum =0
for j in range(n):
arr[i][j] = map(int, input("Input score").strip().split())#[:n]
#the above line causes compilation error
# Find sum of all scores row-wise
for m in arr[i][j]:
sum += m
total[i] = sum1
# Find the max. of total
for j in range(t):
y = max(total[j])
还请提出一种更简洁的方法来解决上述问题。
P.S. 我发现上面的代码几乎是错误的,但是却把我踢到了正确的方向。
将以下修改后的代码与调试过程中出现的问题有关:
max() 使 [] 优先于整数值
当第 13 行错误地表述为:
total = [[[] for i in range (l)] for i in range (n)]
# Input number of tests
t = int(input("Input number of tests"))
# Input number of rows (of students)
n = int(input("Input number of rows"))#.strip().split())
# Input limit on number of students in a row (of students)
l = int(input("Input max. number of studentsin any row"))#.strip().split())
print ('t :',t,'n :',n, 'l :', l)
arr = [[[[] for i in range(l)] for i in range(n)] for i in range(t)]
total = [[[] for i in range (n)] for i in range (t)]
# run input of tests
for i in range(t):
# Input score of each student in the i-th row, out of n
sum =0
for j in range(n):
#for k in range(l):
print("jkl:","i:",i,"j:",j)
arr[i][j] = map(int, input("Input score").strip().split())[:l]
for i in range(t):
for j in range(n):
# Find sum of all scores row-wise
sum = 0
for m in arr[i][j]:
#sum[i][j][] += m
print ('m :', m)
sum += m
#total[i][j] = sum[i][j][]
total[i][j] = sum
for i in range(t):
print("Test no. ", i)
for j in range(n):
#for m in arr[i][j]:
print (arr[i][j])
#print (m)
print("=========")
for i in range(t):
for j in range(n):
print(i,"-",j, total[i][j])
print("::::::")
print("=========")
# Find the max. of total
for i in range(t):
print([m for m in total[i]])
y = max([m for m in total[i]])
print ('i:',i,',', 'max total:',y)
请求 max() 显示的优先级的原因,并在可能的情况下将答案与 CPython 中的底层实现相关联。
【问题讨论】:
标签: python-3.x cpython python-internals