Python嵌套列表处理及第二低分学生查询代码修改求助
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.
咱们来看看你的代码里需要调整的几个地方:
- 你现在每次循环都重新定义
name_list和score_list,这样每次只能存当前输入的单个学生信息,之前的会被覆盖掉,得把这两个列表的初始化放到循环外面 name_list = list(name)这行是把单个名字拆成了字符列表(比如输入"Alice"会变成['A','l','i','c','e']),这完全不对,应该直接把名字添加到列表里- 取第二低分的逻辑要等所有分数都收集完再做,不能放在循环里,不然每次循环都只处理当前一个分数,会报错
- 最后判断学生分数的时候,你拿整个嵌套列表元素
x和分数second比,应该比的是x[1](也就是学生的分数) - 还要记得把符合条件的名字排序后再输出
下面是修改后的代码,每处改动我都加了注释:
if __name__ == '__main__': # 把列表初始化放到循环外面,用来存所有学生的名字和分数 name_list = [] score_list = [] for _ in range(int(input())): name = input() score = float(input()) # 直接把名字和分数添加到列表,不是拆成字符 name_list.append(name) score_list.append(score) # 现在所有分数都收集完了,再去重排序 unique_scores = sorted(list(set(score_list))) second_lowest = unique_scores[1] # 生成嵌套列表,这里zip的是整个名字列表和分数列表,不是单个名字的字符 student_nest = [[x, y] for x, y in zip(name_list, score_list)] # 先收集所有符合条件的名字 target_students = [student[0] for student in student_nest if student[1] == second_lowest] # 按字母排序后逐个打印 for name in sorted(target_students): print(name)
这样调整后,代码就能实现你的需求啦:先收集所有学生信息,找到第二低分,筛选出对应学生,排序后输出。
备注:内容来源于stack exchange,提问作者Ojasvi
相关产品推荐
相关产品推荐

