python-2.7 – Sort lists of lists with two sort criteria

Question:

If I have a list of lists like this:

lista = [['ana','1'], ['joao', '3'], ['rita','2'], ['alice','2']]

I first want to sort the list according to the numbers, so it looks like this:

lista = [['ana','1'], ['rita','2'], ['alice','2'], ['joao', '3']]

Which I did with: listaOrdenada = sorted(lista, key = lambda x: x[1])

But since, in this case, I have two lists with the number '2', I want to sort these two lists alphabetically according to the name, how do I do that?

Answer:

you can do like this

listaOrdenada = sorted(lista, key = lambda x: (x[1], x[0]))

The lambda passed says that the first sort criterion is column 1 and the second sort criterion is column 0 .

Scroll to Top