我应该如何对 Hackerrank 练习挑战嵌套列表的元素进行排序,然后以正确的方式输出第二低的分数?

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

我尝试以多种方式对这个挑战进行排序,但这一次显然我的脚本这次排序方式错误。

挑战在于您输入学生的姓名和分数,然后脚本必须输出分数第二低的学生的姓名,如果有分数相同的学生,也输出他们的名字。但显然它的排序方式是错误的。

这是我的代码:

score_list = []
for n in range(int(input())):
    name = input()
    score = float(input())
    st_score = [name, score]
    score_list.append(st_score)
sortedscore = sorted(score_list, key=lambda x: x[1])
secondguy = []
second_low = sortedscore[1][1]
for i in range(len(sortedscore)):
     if sortedscore[i][1] == second_low:
        secondguy.append(sortedscore[i])
for j in range (len(secondguy)):
    student = secondguy[j][0]
    print(student)

给定的输入是: 5 哈利 37.21 浆果 37.21 蒂娜 37.2 阿克里蒂 41 残酷的 39

预期输出为: 浆果 哈利

但实际上返回的输出是: 哈利 浆果

它以这种方式对元素进行排序:

[['Tina', 37.2], ['Harry', 37.21], ['Berry', 37.21], ['Harsh', 39.0], ['Akriti', 41.0]]

那么到底是什么让这个脚本没有给出正确的响应呢?

python list sorting for-loop nested-lists
1个回答
0
投票

当有很多学生的成绩相同时,需要按姓名排序。您收到订单

Harry, Berry
,但需要
Berry, Harry

如果您使用

key=lambda x: (x[1],x[0])
那么它将按
score
以及
name

排序
sortedscore = sorted(score_list, key=lambda x: (x[1],x[0]))

如果您将其保留为

(score, name)
那么您就不需要
key

score_list = []

n = int(input())
for _ in range(n):
    name = input()
    score = float(input())
    score_list.append( (score,name) )

sortedscore = sorted(score_list))

second_low = sortedscore[1][0]
for score , name in sortedscore:
     if score == second_low:
        print(name)
© www.soinside.com 2019 - 2024. All rights reserved.