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)
1
  • 2
    What's your desired output? Commented Apr 16, 2020 at 8:55

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.