Python 3.x字典与循环应用:计算最佳学生成绩报错排查
问题解决
错误原因
- 原有代码仅遍历输出了每个学生的最低分、最高分,没有做全局的最高分对比,无法筛选出最高分最高的学生
- 遍历过程仅获取了字典的values,没有关联对应的学生姓名,最终无法输出符合要求的学生信息
修正方案
方案1:不修改原成绩字典,直接遍历计算(更简洁)
log = { 'Alex': [3, 7, 11, 10, 8], 'Ben': [6, 12, 4, 9, 9], 'Carla': [5, 10, 7, 5, 9]} # 初始化最优学生信息变量 best_name = "" highest_score = -1 lowest_score = 0 # 遍历字典同时获取学生姓名和对应成绩列表 for name, scores in log.items(): current_max = max(scores) current_min = min(scores) # 对比当前学生最高分是否高于全局最高 if current_max > highest_score: highest_score = current_max lowest_score = current_min best_name = name # 按要求格式输出 print(f"Best student {best_name}, he has the maximum score {highest_score}, minimum score {lowest_score}")
方案2:按照你原有的先转换字典的思路实现
log = { 'Alex': [3, 7, 11, 10, 8], 'Ben': [6, 12, 4, 9, 9], 'Carla': [5, 10, 7, 5, 9]} # 批量更新每个学生的成绩为[最低分, 最高分],避免手动逐个写 for name in log: log[name] = [min(log[name]), max(log[name])] best_name = "" highest_score = -1 lowest_score = 0 # 遍历同时获取姓名和对应的[最低分, 最高分]列表 for name, (cur_min, cur_max) in log.items(): if cur_max > highest_score: highest_score = cur_max lowest_score = cur_min best_name = name print(f"Best student {best_name}, he has the maximum score {highest_score}, minimum score {lowest_score}")
运行结果
两种方案输出均为:
Best student Ben, he has the maximum score 12, minimum score 4
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

