我的函数应该将包含数字列表的列表作为输入。每个数字列表都应代表特定学生在课程中获得的成绩。例如,这是一个四个学生的班级的输入列表:
[[95,92,86,87],[66,54],[89,72,100],[33,0,0]]
我的功能应该每行打印一次,每个学生的平均成绩。我不能假设每个学生的成绩都相同。
这是我到目前为止所拥有的:
def avg(grades):
for average in grades:
return sum(grades) / len(grades)
但是当我通过输入avg([[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]])
进行测试时,它显示了此错误:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
avg([[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]])
File "<pyshell#3>", line 3, in avg
return sum(grades) / len(grades)
TypeError: unsupported operand type(s) for +: 'int' and 'list'
解决方案应该是:
90.0
60.0
87.0
11.0
我该如何解决?
答案 0 :(得分:2)
您需要使用The.Eternal.Evil.of.Asia.1995
Guzoo.1986
而不是<?php
$license_str = "<strong>Code#1: </strong>11516331226428373002<br><strong>Code#2: </strong>11512231686337183002<br><strong>Code#3: </strong>11512231686337183008<strong>Code#4: </strong>11512231686337183007<br>";
$license_str = strip_tags($license_str );
//split by code#number: like, code#1:, code#2:, code#3: etc.
$result = preg_split("/Code#(\d+):/", $license_str, -1, PREG_SPLIT_NO_EMPTY);
echo "<pre>";
print_r($result);
来进行sum(average)
和len(average)
:
average
答案 1 :(得分:2)
grades= [[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]]
def avg(grades):
for average in grades:
print(sum(average) / len(average))
return
avg(grades)
输出:
90.0
60.0
87.0
11.0
答案 2 :(得分:2)
一个简单的解决方案:
students_results = []
def avg3(students):
for student in students:
students_results.append(sum(student) / len(student))
return students_results
arr = [[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]]
print(avg3(arr))
结果:[90.0,60.0,87.0,11.0]