typeerror字符串索引必须是整数而不是str python

时间:2014-08-04 11:18:18

标签: python

我已经定义了一个函数get_class_average(),其中有一个参数"学生"。 students是3名学生的名单:lloyd,alice,tyler,它们是间接词典。 get_average()是一个计算平均值的函数,它运行正常。当我尝试调用函数get_class_average()时,我收到错误:

typeerror string indices must be integers not 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]
}

# Add your function below!
from math import *
def average(numbers):
    total = sum(numbers)
    total = float(total)
    ans = total / len(numbers)
    return ans
num = [1,2,4,5,6]
a = average(num)
print a

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    sum = (0.1*homework) + (0.3 * quizzes) + (0.6 * tests)
    return sum

student = [lloyd, alice, tyler]
for key in student:   
    a = get_average(key)
    print a

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"

avg = get_average(lloyd)
t = get_letter_grade(avg)
print t


def get_class_average(students):
    results = []
    students = [lloyd, alice, tyler]
    a= get_average(students)
    r= results.append(a)
    return r

student = [lloyd, alice, tyler]
for key in student:   
    a = get_class_average(key)

print a

1 个答案:

答案 0 :(得分:0)

您的get_class_average()函数希望通过整个学生列表,而不是每个学生。

删除for key in student:循环:

students = [lloyd, alice, tyler]
a = get_class_average(students)

get_class_average()函数中,您似乎过早地返回; unindent return不成为循环的一部分。 results.append()返回None,因为它会就地改变results

def get_class_average(students):
    results = []
    for key in students:   
        a= get_average(key)
        results.append(a)
    return results

然而,这仍然不计算全班的平均值;它只是将每个学生的平均值收集到列表中。