从文件中返回学生编号和学生平均值

时间:2017-11-02 15:53:52

标签: python python-3.x

对于这个功能,我想让第一个内部列表中的每个学生编号和第二个内部列表中的任务等级的平均值。这是文件。

Last Name,First Name,Student No.,uTORid,A1,A2,A3,A4
Smith, Joe,9911991199,smithjoe9,99,88,77,66
Ash, Wood,9912334456,ashwood,11,22,33,44
Full, Kare,9913243567,fullkare,78,58,68,88

我测试我的功能时出现此错误

line 59, in <module>
marks = float(grades)
builtins.TypeError: float() argument must be a string or a number, not 'list'

有人可以帮我解决这个问题吗?

def student_avg(open_file):
    '''(file) -> list of list

    Given an open class list file, return a list of lists where each 
    inner list is the student number (a str) and the second is the
    average of the assignment grades for that student (a float).
    '''

    new_list = []
    for line in open_file:
        nums_list = line.split(',')
        for item in nums_list:
            stu_num = nums_list[2]
            grades = nums_list[4:]
            marks = float(grades)
            avg = sum(marks)/len(grades)
            new_list.append([stu_num, avg])
    return new_list

2 个答案:

答案 0 :(得分:0)

浮动sum的结果。

def student_avg(open_file):
    '''(file) -> list of list

    Given an open class list file, return a list of lists where each 
    inner list is the student number (a str) and the second is the
    average of the assignment grades for that student (a float).
    '''
    new_list = []
    for line in open_file:
        split = line.split(',')
        student_id = split[2]
        grades = split[4:]
        average = sum(float(g) for g in grades) / len(grades)
        new_list.append([student_id, average])
    return new_list

顺便说一句,我删除了第二个for因为我觉得它与问题不符:你会多次回到同一个学生。

答案 1 :(得分:0)

def student_avg(open_file):
    '''(file) -> list of list

    Given an open class list file, return a list of lists where each 
    inner list is the student number (a str) and the second is the
    average of the assignment grades for that student (a float).
    '''

    new_list = []
    for line in open_file:
        nums_list = line.split(',')
        for item in nums_list:
            stu_num = nums_list[2]
            grades = nums_list[4:]
            avg = float(sum(grades))/len(grades)
            new_list.append([stu_num, avg])
    return new_list

将分子或分母转换为float将解决目的。如果其中一个成绩列表是一个浮点数,那么总和就是浮点数。