我正在创建一个可以回答上述问题的代码,而我做了以下
scores=[23,11,19,13,26]
names1=["joe","tom","bob","fred","barry"]
average=(scores[0]+scores[1]+scores[2]+scores[3]+scores[4])/5
print("the average is",average,"and the following are above average:")
if scores[0] > average:
print(names[0],scores[0])
if scores[1] > average:
print(names[1],scores[1])
if scores[2] > average:
print(names[2],scores[2])
if scores[3] > average:
print(names[3],scores[3])
if scores[4] > average:
print(names[4],scores[4])
但是由于未知原因,它显示IndexError:列表索引超出范围
我不确定如何解决此错误?
答案 0 :(得分:2)
您应该循环在名称和分数对上,为高于平均水平的每个分数打印一行。请注意,内置函数sum
在内部循环得分。
scores = [...]
names1 = [...]
average = sum(scores)/5
print("The average is {} and the following are above average".format(average))
for name, score in zip(names1, scores):
if score > average:
print(name, score)
答案 1 :(得分:0)
有一件事,就是您有一个错字,您的列表被称为names1,而不是名字,因此我将其更改。如果这样做,您的代码将起作用,但是可以通过使用for
循环来使其更好。
这应该有效:
scores=[23,11,19,13,26]
names=["joe","tom","bob","fred","barry"]
average=(scores[0]+scores[1]+scores[2]+scores[3]+scores[4])/5
print("the average is",average,"and the following are above average:")
for i in range(len(scores)):
if scores[i] > average:
print(names[i],scores[i])