【问题标题】:Return the average mark givin the respective lecture返回相应讲座的平均分
【发布时间】:2012-11-09 07:47:34
【问题描述】:

每一行代表一个学生,由一个学号、一个姓名、一个部门代码和一个期中成绩组成,所有这些都用空格分隔。 第一个参数已经完成并且文件已打开并且
第二个参数是段码 这是链接http://www.cdf.toronto.edu/~csc108h/fall/exercises/e3/grade_file.txt

我的代码:

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  

我的索引超出范围。它是否正确?还是我只是打开了错误的文件?
有人可以测试此代码并下载该文件吗?我很确定它应该可以工作,但不适合我。

【问题讨论】:

  • score 应该是 mark(反之亦然)吗?

标签: python list whitespace


【解决方案1】:

好吧,您可以使用print lineprint(line) 来解决索引超出范围错误以探索“行”中的项目数(即split() 的效果)。我建议仔细查看您的 split() 声明...

【讨论】:

    【解决方案2】:

    您似乎忽略了定义其中一些变量(section_codemark 等)的部分代码,但针对其中一些内容进行调整似乎可以正常工作。假设您得到的错误是IndexError: list index out of range,当您尝试按索引访问列表中不存在该索引的元素时,就会发生这种情况。例如:

    >>> 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
    

    因此,在您的代码中,如果 line 少于两个项目,您将收到该错误。我会检查并查看您实际得到的 line 以确保它是您所期望的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2012-10-28
      • 1970-01-01
      相关资源
      最近更新 更多