我是python的初学者,可能会带来一些基本问题。有人可以帮忙吗?
我想获得每个学生的平均值,然后计算这些平均值的平均值。获取" TypeError:字符串索引必须是整数,而不是str"。无法弄清楚它所指的是什么以及如何修改。这是我的代码:
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(numbers):
total = sum(numbers)
total = float(total)
return total/len(numbers)
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return 0.1*homework + 0.3*quizzes + 0.6*tests
def get_class_average(students):
results = []
for student in students:
result = get_average(student)
results.append(result)
return average(results)
students = ["lloyd", "alice", "tyler"]
print get_class_average(students)
答案 0 :(得分:6)
当您在引号中包含名称时,它是字符串文字,而不是变量。
>>> x = 3
>>> x
3
>>> 'x'
'x'
使用students = [lloyd, alice, tyler]
来引用您在上面定义的变量。