How to use multiple keys when sorting?

Question:

There’s this list that I want to sort:

table = [("A", 5, 3), ("B", 5, 6), ("C", 3, 1)]

Inside each tuple, let’s call the elements name, points, ex, in that order.

I want to sort that list by descending order of points, that’s simple enough.

But if points are the same for 2 tuples, I’ll sort those by ascending order of ex.

How can I go about doing this?

Asked By: PositiveBowl7

||

Answers:

You can use the "sorted" built-in function with custom ordering function. If you want to make values to be ordered descendently, it’s sufficient to use negatives of the same values.

sorted(table, key = lambda x: (-x[1], x[2]))

Output:

[('A', 5, 3), ('B', 5, 6), ('C', 3, 1)]
Answered By: lemon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.