【Python】找出排名倒数第二的学生

一、题目

Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.

Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.

Example

records=[["Candy" , 60.0], ["Berry" , 80.0] ,["Aries",80.0]]

The ordered list of scores is [60.0 , 80.0],so the second lowest score is 80.0. There are two students with that sore:

["Berry","Aries"]. Ordered alphabetically, the names are printed as :

Aries

Berry

Input Format

The first line contains an integer N , the number of students .

The 2N subsequent lines describe each student over 2 lines.

- The firest line contains a student's name.

- The second line contains their grade.

Sample Input 

5

Harry

37.21

Berry

37.21

Tina

37.2

Akriti

41

Harsh

39

Sample Output 

Berry

Harry

二、代码 

题目要求找出班级中排名倒数第二的学生名单,并按字母顺序逐行打印他们的名字:

if __name__ == '__main__':
    # 创建列表,存储学生姓名和分数
    students = []
    
    for _ in range(int(input())): 
        name = input()
        score = float(input())
        students.append([name,score])
    
    # 将学生分数从低到高排列
    students.sort(key = lambda x: x[1] ,reverse = False)
    
    second_lowest_score = None
    
    # 从第二个学生开始遍历students列表,查找倒数第二的分数
    for i in range(1,len(students)):
        if students[i][1] != students[i-1][1] :
            second_lowest_score = students[i][1]
            break
    
    # 找到分数为倒数第二的所有学生的姓名,并按字母顺序排序
    second_lowest_students = sorted([stu[0] for stu in students if stu[1] == second_lowest_score])
    
    for name in second_lowest_students:
        print(name)

三、解读

        1. students[i][1]

                * 代码表示访问 students 列表中第 i 个学生(注意索引从0开始)的分数

                * students[i] 表示访问列表中第 i 个元组

                * [1] 表示访问元组中的第二个元素

        2. for _ in range(int(input())):

                * 循环语句中 _ 是一个占位符,表示在这个循环中不需要使用循环变量。

                * int(input()) 调用input() 函数获取用户输入的字符串,然后用int()函数将字符串转换为整数。而这个整数将决定循环次数。

                * range(int(input()))) : range() 函数生成一个从 0 到 "用户输入的整数" 减1 的整数序列。例如,用户输入5,则range(5) 生成一个序列 [ 0, 1, 2, 3, 4 ]。

        3. students.append([name, score])

                * 这行代码在每次循环中执行,将一个包含学生和分数( [name, score] ) 的元组添加到 students 列表中。

                * append() 方法将这个元组添加到 students 列表的末尾。

        4. students.sort(key=lambda x: x[1], reverse=False)

                * 这行代码对 students 列表进行排序

                * key = lambda x : x[1]   这是一个匿名函数,制定排序的依据为每个元组的第二个元素( x[1] ),即学生的分数。

                * reverse=False  这个参数指定排序的方向为升序,既分数从低到高排序。也可以忽略不写。


 

  • 21
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值