-1

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?

sedavidw
  • 11,116
  • 13
  • 61
  • 95

1 Answers1

2

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)]
lemon
  • 14,875
  • 6
  • 18
  • 38