如何找到多维列表的平均值?

时间:2016-11-17 08:30:06

标签: python list average

我希望找到平均总数'对于班级的考试成绩。我运行我的程序,但继续得到" TypeError:不支持的操作数类型+:' int'和' str'"。

def newRecord(students,tests):
  students = int(input('How many students are in your class? '))
  tests = int(input('How many tests have you given? '))

  record = []
   for i in range(students):
    rec_line = []
   for j in range(tests+1):
    rec_line.append(0)
   record.append(rec_line)
  print('record:',record)
  print('modified record:',record)

  for A in range (students):
     record[A][0] = input('Please enter student {} name '.format(A+1))
    for B in range (1, tests+1):
        record[A][B] = input ('Please enter test score  {} '.format(B))
  print (record)

  total= float(sum(record))/ len(record)
  print ('Average is: ',total )

1 个答案:

答案 0 :(得分:0)

每个测试结果都需要转换为intfloat才能对它们执行数学函数。在上面的示例中,您还要查找学生的姓名,当您尝试计算“平均值”时会抛出错误。

def newRecord(students,tests):
    students = int(input('How many students are in your class? '))
    tests = int(input('How many tests have you given? '))

record = []
for i in range(students):
    rec_line = []
    for j in range(tests+1):
        rec_line.append(0)
    record.append(rec_line)
print('record:',record)
print('modified record:',record)

for A in range (students):
    record[A][0] = input('Please enter student {} name '.format(A+1))
    for B in range (1, tests+1):
        record[A][B] = input ('Please enter test score  {} '.format(int(B)))
print(record)

total= sum([int(score) for score in rec[1:] for rec in record])/len([int(score) for score in rec[1:] for rec in record])
print('Average is: ',total )

使用示例:

record: [[0, 0, 0], [0, 0, 0]]
modified record: [[0, 0, 0], [0, 0, 0]]
Please enter student 1 name Alice
Please enter test score  1 2
Please enter test score  2 3
Please enter student 2 name Bob
Please enter test score  1 4
Please enter test score  2 5
[['Alice', '2', '3'], ['Bob', '4', '5']]
Average is:  3.5