python: how to sort a complex list on two different keys

You may sort the list twice to get the result, just reverse the order:

import operator

l = [[name_d, 5], [name_e, 10], [name_a, 5]]

l.sort(operator.itemgetter(1))
l.sort(operator.itemgetter(0), reverse=True)

Then you will get the sorted list as expected.


Sort functions in python allow to pass a function as sort key:

l = [[name_d, 5], [name_e, 10], [name_a, 5]]
# copy
l_sorted = sorted(l, key=lambda x: (x[1] * -1, x[0]))
# in place
l.sort(key=lambda x: (x[1] * -1, x[0]))

Edits:
1. Sort order
2. Demonstrate copy and in place sorting

Tags:

Python

Sorting