所以这是我到目前为止的python代码。我想使用这些词典并将它们列入学生列表。我对如何将它们运行到getAverage()
函数并生成此结果
Name: Alice
Homework: [100.0, 92.0, 98.0, 100.0]
Quizzes: [82.0, 83.0, 91.0]
Tests: [89.0, 97.0]
For Alice the average is:91.14999999999999
Name: Lloyd
Homework: [90.0, 97.0, 75.0, 92.0]
Quizzes: [88.0, 40.0, 94.0]
Tests: [75.0, 90.0]
For Lloyd the average is:80.55
Name: Tyler
Homework: [0.0, 87.0, 75.0, 22.0]
Quizzes: [0.0, 75.0, 78.0]
Tests: [100.0, 100.0]
For Tyler the average is:79.9
这是我到目前为止所做的代码:
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]}
rich = {
"name": "Rich",
"homework": [95.0, 93.0, 81.0, 94.0],
"quizzes": [88.0, 55.0, 77.0],
"tests": [80.0, 95.0]}
josh = {
"name": "Josh",
"homework": [93.0, 94.0, 74.0, 99.0],
"quizzes": [87.0, 47.0, 92.0],
"tests": [70.0, 88.0]}
def average(n):
count = float(len(n))
total = float(sum(n))
return total/count
def getAverage(**names):
homework = average(names[homework])
quizzes = average(names[quizzes])
tests = average[names[tests]]
return float((.1*homework +.3*quizzes + .6*tests)/3)
students = [rich, josh, lloyd]
答案 0 :(得分:0)
将getAverage函数修改为此(删除**)
def get_average(names):
homework = average(names['homework'])
quizzes = average(names['quizzes'])
tests = average(names['tests'])
return (0.1*homework + 0.3*quizzes + 0.6*tests) / 3
for student in [rich, josh, lloyd]:
print student['name'], get_average(student)
其他几点:
average
功能答案 1 :(得分:0)
你很近但你需要做一些事情。首先从getAverage
删除**。接下来删除返回时的/3
。同时将此行[]
上的外()
更改为average[names[tests]]
。然后修复缩进。
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]}
rich = {
"name": "Rich",
"homework": [95.0, 93.0, 81.0, 94.0],
"quizzes": [88.0, 55.0, 77.0],
"tests": [80.0, 95.0]}
josh = {
"name": "Josh",
"homework": [93.0, 94.0, 74.0, 99.0],
"quizzes": [87.0, 47.0, 92.0],
"tests": [70.0, 88.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]}
taylor = {
"name": "Taylor",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]}
def average(n):
count = float(len(n))
total = float(sum(n))
return total/count
def getAverage(names):
homework = average(names['homework'])
quizzes = average(names['quizzes'])
tests = average(names['tests'])
return float((.1*homework +.3*quizzes + .6*tests))
students = [rich, josh, lloyd, alice, taylor]
for student in students:
avg=getAverage(student)
print('Name: '+student['name'])
print('Homework: '+str(student['homework']))
print('Quizzes: '+str(student['quizzes']))
print('Tests: '+str(student['tests']))
print('For '+student['name']+' the average is: '+str(avg)+'\n')