我试图返回学生的名字和他们的分数总和,以获得最高的总分数。 我的代码在下面
代码:
# student_grades contains scores (out of 100) for 5 assignments
student_grades = {
'Andrew': [56, 79, 90, 22, 50],
'Nisreen': [88, 62, 68, 75, 78],
'Alan': [95, 88, 92, 85, 85],
'Chang': [76, 88, 85, 82, 90],
'Tricia': [99, 92, 95, 89, 99]
}
# calculate the top student and their total points
list_of_student_grades = list(student_grades.items())
top_student = tuple([(name, sum(grades)) for (name, grades) in list_of_student_grades if
sum(grades) == max([sum(grades) for name, grades in list_of_student_grades])])
print(list_of_student_grades)
print(top_student)
输出:
[('Andrew', [56, 79, 90, 22, 50]), ('Nisreen', [88, 62, 68, 75, 78]), ('Alan', [95, 88, 92, 85, 85]), ('Chang', [76, 88, 85, 82, 90]), ('Tricia', [99, 92, 95, 89, 99])]
(('Tricia', 474),)
我有两个问题。。。 首先,为什么输出不仅仅是('Tricia',474)(为什么是额外的逗号和括号集)? 第二,有没有更好的办法
提前谢谢你
您创建了一个只包含一个元组的列表,当传递给
tuple
时,该列表将生成一个只包含一个元组的元组您真正想要的是名称/总和对列表的最大值,最大值被定义为具有最大总和的对
一种可能的替代方法是简单地计算具有最高总和的学生的姓名,然后重新计算其总和以构建所需的元组。两次计算Tricia的分数是多余的,我不知道这看起来是否更好,但我觉得这足够有趣
相关问题 更多 >
编程相关推荐