Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回各讲座的平均分数_Python_List_Whitespace - Fatal编程技术网

Python 返回各讲座的平均分数

Python 返回各讲座的平均分数,python,list,whitespace,Python,List,Whitespace,每一行代表一名学生,由学生编号、姓名、组别代码和期中成绩组成,全部用空格分隔。 第一个参数已经完成,并且文件已打开并关闭 第二个参数是节代码 这是链接 我的代码: def average_by_section(the_file, section_code): '''(io.TextIOWrapper, str) -> float Return the average midtermmark for all students in that section

每一行代表一名学生,由学生编号、姓名、组别代码和期中成绩组成,全部用空格分隔。 第一个参数已经完成,并且文件已打开并关闭 第二个参数是节代码 这是链接

我的代码:

def average_by_section(the_file, section_code):  
    '''(io.TextIOWrapper, str) -> float  
    Return the average midtermmark for all students in that section  
    '''  
        score = 0  
        n = 0  
        for element in the_file:  
            line = element.split()  
            if section_code == line[-2]:  
                mark = mark + float(line[-1])  
                n += 1  

        lecture_avg = mark / n  
        return lecture_avg  
我得到一个超出范围的索引。这是正确的吗?还是我只是打开了错误的文件?
有人能测试这个代码并下载那个文件吗?我很确定它应该能工作,但对我来说不行。

好吧,你可以用打印行或打印行来解决索引超出范围的错误,以了解行中的项目数,即拆分的效果。我建议仔细看看你的拆分语句…

看起来你忽略了代码中定义一些变量的部分,比如代码部分、标记等,但是针对其中一些内容进行调整似乎可以正常工作。假设您得到的错误是IndexError:list index超出范围,则当您尝试按索引访问列表中不存在该索引的元素时会发生这种情况。例如:

>>> l = ['one']
>>> l[0]
'one'
>>> l[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> l[-1]
'one'
>>> l[-2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
所以,在您的代码中,若行少于两个项目,您将得到该错误。我会检查并看看你们在这条线上得到了什么,以确保它是你们所期望的。

分数应该是马克还是反之亦然?