2

I am trying to sort a list composed of names and grades:

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

I want to sort them first according to the grades and then if the grades are the same, according to the alphabetical order of their names. I tried the following code but it is not working for the name sorting part. Can you tell me the problem please. Thank you

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

score_list.sort(key = lambda x: (x[1], x[0]), reverse=True)
k1m190r
  • 1,213
  • 15
  • 26
ezgi koker
  • 93
  • 4

1 Answers1

1

THE PERFECT SOLUTION (1st answer from this answer)

score_list = sorted(score_list,key = lambda x: (-x[1], x[0]))

or (my way):

score_list = [j[::-1] for j in sorted([i[::-1] for i in l],key=lambda x: (-x[0],x[1]))]

gives: your desire:

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

EXAMPLES
Here is how you do that:

sort_ list = [j[::-1] for j in sorted([i[::-1] for i in l])]

This gives:

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

Here:

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

Now if you want it in descending order:

sort_ list = [j[::-1] for j in sorted([i[::-1] for i in l],reverse = True)]

This gives:

[['Akriti', 41.0], ['Harsh', 39.0], ['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2]]
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34