包含列表和字典的python代码

时间:2015-07-11 20:11:41

标签: python list dictionary

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)
    avg=float(total)/len(numbers)
    return avg
students=[lloyd,alice,tyler]
def get_average(student):
    for a in student:
        homework=average(a["homework"])
        quizzes=average(a["quizzes"])
        tests=average(a["tests"])
        student= .1 * homework + .3 * quizzes + .6 * tests
    return student

print get_average(students)

上面的代码只输出一个学生Tyler的平均值,这是此列表students=[lloyd,alice,tyler]中的最后一个。

但是我认为这个列表不起作用,但Codecademy确实在他们的课程中使用了这个列表。 我希望打印所有三个学生的平均值。请帮助..提前谢谢。

1 个答案:

答案 0 :(得分:0)

您只使用student的最后一个值,如果您希望全部查看,则需要在每次迭代中附加所有学生值:

def get_average(students):
    students_avs = []
    for a in students:
        homework = average(a["homework"])
        quizzes = average(a["quizzes"])
        tests = average(a["tests"])
        student= .1 * homework + .3 * quizzes + .6 * tests
        students_avs.append(student) # append each result
    return students_avs

输出:

In [13]: get_average(students)
Out[13]: [80.55, 91.14999999999999, 79.9]

student= .1 * homework + .3 * quizzes + .6 * tests指向每次迭代的新值,因此从逻辑上讲,您只能看到为最终学生计算的最后一个值,因为您从未在自己的代码中保存每次迭代的值。

您还可以返回列表理解:

def get_average(students):
    return [.1 * average(a["homework"]) + .3 * average(a["quizzes"]) + .6 * average(a["tests"])
            for a in students]

另一种选择是对单个学生使用get_average并在列表comp中调用该函数:

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    student = .1 * homework + .3 * quizzes + .6 * tests
    return student


out = [get_average(d) for d in students]
print(out)