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 (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

任何人都可以帮忙吗?

4

1 回答 1

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)
于 2013-08-31T08:46:07.150 回答