我将如何通过列表中的第二个元素对嵌套列表进行排序,然后输出整个列表中第二个最低的元素?

问题描述 投票:0回答:1

这是一个HackerRank Python练习探针:HackerRank Nested List Problem

我通过了10个测试用例中的8个,但其中2个得到了错误的答案。有什么建议吗?

这是我的提交代码:

students = []
current_list = []

if __name__ == '__main__':
    for _ in range(int(input())):
        name = input()
        score = float(input())
        current_list = [name, score]
        students.append(current_list)

students = sorted(students, key = lambda x: x[1])

#print(students)
#print(students[1][0])

if students[2][1] == students[1][1]:
  final_list = students[1:3]
  final_list_sorted = sorted(final_list, key = lambda x: x[0])
  print(final_list_sorted[0][0])
  print(final_list_sorted[1][0])
else:
  print(students[1][0])
nested-lists
1个回答
0
投票

我认为您在这里的问题是关于HackerRank问题描述的这一部分-

注意:如果有多个同等级的学生,请订购他们的按字母顺序命名,然后将每个名称打印在新行上。

-您的代码假定“ multiple”始终为2,而可能为3或更多,在这种情况下,您的输出将不正确。另一个问题是您的代码还假设永远不会有多个分数最低的学生。

[我还将注意,如果您使用[score, name]而不是[name, score]作为每个学生的条目,则students.sort()students = sorted(students)会自动按等级升序排序,其次按名称升序排序,为您节省一些时间步骤。

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