How to sort a list of tuples by second element but with condition

Viewed 68

Let's say I have this list of tuples:

[(30, 'B'), (50, 'B'), (40, 'C'), (10, 'A'), (80, 'A'), (5, 'A')]

I need to sort the tuples by their second element in descending order but with the condition that all of the tuples with an identical second element are next to one another.

So, it should look like

[(80, 'A'), (10, 'A'), (5, 'A'), (50, 'B'), (30, 'B'), (40, 'C')]

How can I do this?

2 Answers

You want to sort by the second element, then the negative of the first:

>>> values = [(30, 'B'), (50, 'B'), (40, 'C'), (10, 'A'), (80, 'A'), (5, 'A')]

>>> sorted(values, key=lambda value: (value[1], -value[0]))
[(80, 'A'), (10, 'A'), (5, 'A'), (50, 'B'), (30, 'B'), (40, 'C')]

The key argument to sorted needs to be a function which converts each value into the value you want to compare.

I pass in a lambda function which takes the value (a tuple, e.g. (40, 'C')), and then returns ('C', -40). Python then compares the first reversed value, 'C', and if it matches, compares the second value -40.

Use lambda for such needs:

a = [(30, 'B'), (50, 'B'), (40, 'C'), (10, 'A'), (80, 'A'), (5, 'A')]
a.sort(key=lambda x: (x[1], -x[0]))
print(a)

Output:

[(80, 'A'), (10, 'A'), (5, 'A'), (50, 'B'), (30, 'B'), (40, 'C')]
Related