以下代码出错,我在过去两天内无法调试。 我是一个完全的初学者,在学习了c之后开始使用python。
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)
result = (total/len(numbers))
return result
def get_average(stud):
homework=average(stud["homework"])
quizzes=average(stud["quizzes"])
tests=average(stud["tests"])
return (.1*homework + .3*quizzes + .6*tests)
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80 and score < 90:
return "B"
elif score >= 70 and score < 80:
return "C"
elif score >= 60 and score < 70:
return "D"
else:
return "F"
result = get_average(lloyd)
print get_letter_grade(result)
students = {"name": ["lloyd", "alice", "tyler"]}
def get_class_average(students):
results = []
for student in students:
final = get_average(student["name"])
results.append(final)
return average(results)
print get_class_average(students["name"])
print get_letter_grade(get_class_average(students))
错误是(忽略上面代码中的不正确缩进):
追踪(最近一次通话): File&#34; python&#34;,第51行,in 在get_class_average中的文件&#34; python&#34;,第47行 TypeError:字符串索引必须是整数,而不是str
答案 0 :(得分:1)
get_class_average(students["name"])
将字符串列表传递给函数。 for student in students:
循环显示该列表,现在student
是单字符串,即列表中的元素。student["name"]
,它尝试使用另一个字符串索引字符串student
。 这是不可能的,甚至没有意义,因此错误。
答案 1 :(得分:0)
社区需要缩进才能运行代码。 ForceBru是对的,你不能声明一个字符串值列表
students = {“name”:[“lloyd”,“alice”,“tyler”]}来实现这个目标 对于学生: 最终= get_average(学生[ “名称”])
既然你已经宣布了上面的学生,为什么不呢 学生= {“姓名”:[劳埃德,爱丽丝,泰勒]}
答案 2 :(得分:0)
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]}
def average(numbers):
return (float(sum(numbers)) / len(numbers))
def get_average(stud):
homework, quizzes, tests = average(stud["homework"]), average(stud["quizzes"]), average(stud["tests"])
return (.1*homework + .3*quizzes + .6*tests)
def get_letter_grade(score):
if score >= 90:
return "A"
elif score < 90 and score >= 80:
return "B"
elif score >= 70 and score < 80:
return "C"
elif score >= 60 and score < 70:
return "D"
elif score < 60:
return "F"
result = get_average(lloyd)
print(get_letter_grade(result))
students = [lloyd, alice, tyler]
def get_class_average(students):
results = []
for student in range(len(students)):
final = get_average(students[student])
results.append(final)
return average(results)
print(get_class_average(students))
print(get_letter_grade(get_class_average(students)))