我最近开始学习Python,并且我被分配了创建一个平均字典成绩的函数的任务。
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def average(grades):
total = 0
grades.sum() = total
total.float() = total
total = total / len(grades)
return total
然而,当执行该功能时,我收到错误,"不能分配给功能调用"这是什么意思,我该如何解决?
答案 0 :(得分:2)
我猜你想要将成绩列表传递给average()
函数。
您在grades.sum() = total
和total.float() = total
你(可能)想要这样的东西:
def average(grades):
total = sum(grades)
return float(total) / len(grades)
你可以这样称呼这个函数:
avg = average(alice["homework"])
total = sum(grades)
表示计算grades
中值的总和,并将结果存储在名为total
的变量中。函数调用sum(grades)
提出一个问题,在Python中(像大多数其他编程语言一样)我们在=
符号的右侧侧写下问题,并且将答案放在=
符号的左侧侧。但是你的代码反过来了。
答案 1 :(得分:0)
您正在为内置函数的返回值赋值,这是不可能的。试试这个
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
def average(grades):
total = 0
total = grades.sum()
total = total.float()
total = total / len(grades)
return total
答案 2 :(得分:0)
而不是:
grades.sum() = total
你宁愿这样做:
total = grades.sum()
如果你想深入挖掘,这里有 explanation of the whys and hows 。