3

I have a list of nested lists:

e = [['Tina', 37.2], ['Harsh', 39], ['Harry', 37.21], ['Berry', 37.21], ['Akriti', 41]]

How do you sort by numerical value, yet the names 'follow' the 'grade'? I could use dict, but I think it misses the point.

3 Answers 3

2

You could sort the list with a custom key:

result = sorted(e, key = lambda x : x[1])
Sign up to request clarification or add additional context in comments.

Comments

1
e.sort(key=lambda item: item[1])

Comments

0

In your example Harry and Berry have the same value.

If you want ties to be sorted by name, a variation of the answers you got already would be something like this:

e = [['Tina', 37.2], ['Harsh', 39], ['Harry', 37.21], ['Berry', 37.21], ['Akriti', 41]]

e.sort(key=lambda x:(x[1], x[0]))

print(e)
#[['Tina', 37.2], ['Berry', 37.21], ['Harry', 37.21], ['Harsh', 39], ['Akriti', 41]]

2 Comments

Why not just the much simpler lambda x: (x[1], x[0])?
Only because I didn't think about it :) Will edit. Thanks.

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.