为什么此代码仅在我的 CA 上 运行 时抛出 IndexError?

Why does this code throw an IndexError only when run on my CA?

我有一个包含姓名和分数的 .csv 文件。以下是文件内容(名称和分数在不同的列中):

Bob 1
Dave 6
Linda 9.76
Andy 90
hilary 87
mathew 6.4576589 

程序应从最高到最低显示分数。像这样:

Bob 1
Dave 6
mathew 6.4576589 
Linda 9.76
hilary 89
Andy 90

我已经尝试这个很久了。下面是我的代码:

import csv
import operator
out_file = open('class1_scores_max.csv','r')
scores1 = csv.reader(out_file,delimiter=',')
sort = sorted(scores1,key = lambda x: float(x[1]))
for eachline in sort:
    final = eachline[0]," ",eachline[1]
    print (''.join(final))

这在单独的 python 文件中完美运行,但在我在学校的主要控制评估中出现错误:

IndexError: list index out of range

在我在学校的主要代码中,它是定义(子例程)的一部分。谁能帮忙?

根据您提供的内容,您将在以下两行中的任何一行得到 IndexError

sort = sorted(scores1,key = lambda x: float(x[1]))

    final = eachline[0]," ",eachline[1]

我怀疑你 IndexError 在第一行,因为在第二行出现 IndexError 似乎暗示它也会出现在第一行。

您可以通过在排序和打印之前确保每行中有两个元素来解决此问题。

sort = sorted([x for x in scores1 if len(x) == 2], key = lambda x: float(x[1]))

这也是学习调试基础知识的好时机。假设您没有来自 Internet 的帮助并且不得不自己调试这个问题。添加一些打印语句是调试代码的最快和最简单的方法之一。例如,

import csv
import operator
out_file = open('class1_scores_max.csv','r')
scores1 = csv.reader(out_file,delimiter=',')
for score in scores1:
    print score
sort = sorted(scores1,key = lambda x: float(x[1]))
for eachline in sort:
    final = eachline[0]," ",eachline[1]
    print (''.join(final))

注意我插入以下行的位置:

for score in scores1:
    print score

当您尝试访问 [=18= 中的元素的第一个和第二个元素时,这将允许您查看 scores1 中是否有可能导致 IndexError 的内容=].