我对字典有一些问题 这是我的代码:
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 (number):
total = 0.0
for i in number:
total = total + number[i]
return total/ len(number)
def get_average(student):
return average(student["homework"])*0.1 + average(student["quizzes"])*0.3 + average(student["tests"])*0.6
print get_average(tyler)
错误:TypeError: list indices must be integers, not float
有人可以帮忙吗?
答案 0 :(得分:0)
问题在于您的average
功能:
for i in number:
total = total + number[i]
在此循环中,i
设置为number
数组中的每个值,而不是索引。
您的循环可能只是:
for i in number:
total = total + i
同样,这是python,而不是for
循环,你可以使用sum()
函数:
def average(number):
return float(sum(number))/len(number)