Sunday, 15 September 2013

Sorting a list of tuples on multiple keys

Sorting a list of tuples on multiple keys

I want to sort a list of tuples where the tuples are of type (a, b) where
a and b are integers. The key for sorting the list should be the
difference between a and b i.e a - b and to break the ties, it should sort
on a, both in descending order.
I tried using this:
def sort(list):
scores = sorted(list, key=lambda list: list[0], reverse=True)
scores = sorted(list, key=lambda list: (a - b), reverse=True)
But this seems to sort on the difference and reorder the elements sorted
on the first element of the tuple.
For example:
The input:
[(75, 10), (88, 4), (93, 9), (80, 5), (94, 10)]
The expected output:
[(94, 10), (93, 9), (88, 4), (80, 5), (75, 10)]
The obtained output:
[(93, 9), (88, 4), (94, 10), (80, 5), (75, 10)]

No comments:

Post a Comment