一、题目
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 这个参数指定排序的方向为升序,既分数从低到高排序。也可以忽略不写。