从文件计算类avg

时间:2017-11-03 00:34:14

标签: python python-3.x

对于这个函数,我想要每个赋值的类平均值。当我尝试测试我的功能时,我收到此错误。有人可以帮我解决这个问题吗? 我想通过列,并有类似的东西。拆分列表后,我想交错分配的等级并添加相应的项目。我该怎么做然后计算平均值? 我希望[99,88,77,66] [11,22,33,44] [78,58,68,88]进入[99,11,78] [88,22,58] [77,33] ,68] [66,44,88]

  

对于范围内的项目(grades_list [4:]):   builtins.TypeError:'list'对象不能解释为整数

这是我的功能文件。

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


def class_avg(open_file):
    '''(file) -> list of float
    Return a list of assignment averages for the entire class given the open
    class file. The returned list should contain assignment averages in the 
    order listed in the given file.  For example, if there are 3 assignments 
    per student, the returned list should 3 floats representing the 3 
    averages.
   [a1_avg, a2_avg, a3_avg, a4_avg]
   [62.666666666666664, 56.0, 59.333333333333336, 66.0]
    '''
    new_list = []
    for line in open_file:
        grades_list = line.split(',')
    for item in range(grades_list[4:]):
    total = sum(grades_list[4:][item])
   avg = total/len(grades_list[4:])
   new_list.append(avg)
   return new_list

2 个答案:

答案 0 :(得分:0)

创建一个2d列表..... 读取所有行,然后只对要输出的colomns进行计算... 访问该列类似于

#example in python console
>>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> new_list = [item[1] for item in list]
>>> new_list
[2, 5, 8]

答案 1 :(得分:0)

您的代码中存在一些问题。

  • 您需要跳过标题行("姓氏,名字,学号,uTORid,A1,A2,A3,A4和#34;)
  • 您还计算每位学生的多个平均值(对于第一行,您的代码基本上是(9 + 9) / 2(8 + 8) / 2等)
  • 此外,您似乎正在尝试读取列,但这不起作用

这样的事可能适合你:

averages = []

with open('class_avg.csv') as fp:
    next(fp)  # skip header row
    reader = csv.reader(fp)
    for student_row in reader:
        grades = student_row[4:]  # extract columns 4, 5, 6, and 7 all at once
        total = sum(float(grade) for grade in grades)
        average = total / len(grades)
        averages.append(average)

print(averages)