python - 如何使用 python 打印学生成绩的最高分和姓名?
问题描述
使用 python,我正在创建一个接收列表列表作为参数的代码。此列表列表包含学生的姓名和年级。该功能还必须打印成绩最好的学生的姓名及其最好成绩。当我创建代码并尝试运行它时,什么都没有发生,有没有办法改进我的代码?我想要的输出是“最好的学生是:9.6 的卡罗琳”
students=[["steve", 9.0], ["ben", 9.5], ["Caroline",9.6],["Tim", 9.1]]
highest_grade=[]
lowest_grade=[]
def best():
i = 1
max = min = students[0]
# first, calculate the max and min.
while i < len(students): # (possible improvement: replace this with a for loop)
if students[i] > max:
max = students[i] # replace max with the new max
if students[i] < min:
min = students[i] # replace min with the new min
i += 1
highest_grade.append(max)
lowest_grade.append(min)
print("The best student is:",best())
解决方案
您可以做一些事情来改进它。您找到最低分数但不使用它,所以我不确定您是否需要它。如果您确实需要它,您可以将其添加到您的return
声明中。这是一个建议的方法,应该很容易遵循:
students = [["steve", 9.0], ["ben", 9.5], ["Caroline", 9.6], ["Tim", 9.1]]
def best(students):
highest_grade_name = None
lowest_grade_name = None
my_max_score = -float("inf")
my_min_score = float("inf")
for name, score in students:
if score > my_max_score:
my_max_score = score
highest_grade_name = name
if score < my_min_score:
my_min_score = score
lowest_grade_name = name
return my_max_score, highest_grade_name
best_name, best_score = best(students)
print(f"The best student is {best_name} with a score of {best_score}")
推荐阅读
- mongodb - 如何在生产和查询中向 mongodb 添加新字段?
- c - C - 使用 sprintf() 在字符串中添加前缀
- mysql - 如何在 sql 脚本文件中删除或添加列?
- angular - 如何将自定义工具栏按钮添加到 ckeditor/ckeditor5-angular
- javascript - 返回给我一个完整的功能,而不是价值
- c# - 合并多个 C# 对象
- java - 即使存在,Spring Boot 也要求添加 bean
- php - 数据未提取到下拉列表中
- python - ParseError: not well-formed (invalid token) using ElementTree
- vue.js - 如何在 Vuex 操作完成之前阻止 Vue 生命周期继续进行?