列表索引必须是整数而不是 str python 错误

list indices must be integers not str python error

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]
}

# Add your function below!

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"])
    print student["name"]
    return .1*homework+.3*quizzes+.6*tests

def get_letter_grade(score):
    if score >= 90: 
        return "A"
    elif score >= 80: return "B"
    elif score >= 70 : return "C"
    elif score >= 60 : return "D"
    else : return "F"

results=[] 

def get_class_average(students):
    results.append(get_average(students))
    return average(results)



qq=[lloyd,alice,tyler]


for x in qq:
    get_class_average(x)
    s= get_average(x)
    print s, get_letter_grade(s) 
    print

print results , "Total class average is %s" % average(results)
#

上面的程序虽然给出了正确的结果,但却给我以下错误: get_class_average([alice]) 导致错误:列表索引必须是整数,而不是 str

输出结果如下:

Lloyd
Lloyd
80.55 B

Alice
Alice
91.15 A

Tyler
Tyler
79.9 C

[80.55, 91.14999999999999, 79.9] Total class average is 83.8666666667
None

您可能想要的是所有学生的平均值,例如:

def get_class_average(students):
    student_averages = list(get_average(student) for student in students)
    return average(student_averages)

get_class_average(qq)

输出:

Lloyd
Alice
Tyler
83.86666666666666

所以问题是您对 get_class_average 的实现。

更新:

您的代码还可以进一步简化:

results = [get_average(student) for student in qq]
print results , "Total class average is %s" % average(results)