1

I have a list of tuples that contains (name, score).
I want to sort the list on the second element (reverse = True) and if two names are similar then sort it on first element but not using reverse.
I have problem with the second part of the task that i couldn't find any solution by myself and i couldn't find any solution by myself.
Thanks for considering my question.

Let's say this is the following list:

averages = [('Ryan',7), ('Brian',11), ('Aiden',11), ('Jack',7), ('Mia',20)]

I'm using lambda for it as below:

averages.sort(key=lambda x: (x[1],x[0]),reverse=True)

#output:
[('Mia', 20), ('Brian', 11), ('Aiden', 11), ('Ryan', 7), ('Jack', 7)]

But the output that i want is:

[('Mia', 20), ('Aiden', 11), ('Brian', 11), ('Jack', 7), ('Ryan', 7),]
0

1 Answer 1

0

Try this:

averages.sort(key=lambda x: (-x[1], x[0]))
Sign up to request clarification or add additional context in comments.

2 Comments

Don't just post code, explain how it solves the problem.
@Barmar his code only misses a - probably just a typo. There's not much to explain. Only that -x[1] sorts the list in descending order by the second element of each tuple

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.