Nestled Lists (Python) - 黑客排名挑战问题

问题描述 投票:0回答:1
n = int(input())

students_list = [ ]

#Create arrays according to the number mentioned in the first input
#Distribute the first (name) and second (grade) value to the first array and so on until all the arrays are finished
for _ in range(0,n):
    name = input()
    grade = float(input())
    students_list.append([name,grade])

#Sort grades by lowest to highest    
students_list = sorted(students_list, key=lambda student: student[1])

#Assign value to the second lowest grade
lowest_grade=students_list[0][1]

second_lowest_grade = None

for name, grade in students_list:
    if grade < lowest_grade:
        second_lowest_grade = grade

print(second_lowest_grade)

挑战是: -首先输入一个数字n(数组/列表的数量) -然后输入每个学生的姓名和成绩。学生名单应为[姓名,年级],[姓名,年级]等。 -那么你必须获得学生获得的第二低的成绩 -最后打印成绩第二低的学生的姓名(按字母顺序排列)。

我陷入了挑战的前最后阶段,我不知道如何解决它。我需要帮助

python list nested
1个回答
0
投票

当您需要将不同的键映射到值(在您的情况下可以是学生列表)时,字典非常有用。您可以将代码修改为:

n = int(input())

students_list = [ ]

#Create arrays according to the number mentioned in the first input
#Distribute the first (name) and second (grade) value to the first array and so on until all the arrays are finished
for _ in range(0,n):
    name = input()
    grade = float(input())
    students_list.append([name,grade])

# You can use a dict to get unique grades mapped to students
students_dict = {} # format: {stud_grade: [stud1, stud2], stud_grade2: [stud3], ...}
for stud_name, stud_grade in students_list:
    if stud_grade not in students_dict:
        students_dict[stud_grade] = []
    students_dict[stud_grade].append(stud_name)

sorted_student_list = sorted(students_dict.items())

# Add error handling if there is a risk of less than 2 distinct scores.
print(f"Next lowest score: {sorted_student_list[1][0]}")
print(f"Students with next lowest score: {sorted_student_list[1][1]}")

希望这对您有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.