首页 > 解决方案 > 如何使用 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())

标签: pythonlistnested-lists

解决方案


您可以做一些事情来改进它。您找到最低分数但不使用它,所以我不确定您是否需要它。如果您确实需要它,您可以将其添加到您的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}")

推荐阅读