Sort lists with two sort criteria

Asked

Viewed 683 times

4

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, to look like this:

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

That 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 this?

  • Related: http://answall.com/questions/101159/ordernar-listers

1 answer

3


You can do it like this

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

The lambda past says that the first ordering criterion is the column 1 and the second ordering criterion is the column 0.

  • I think I get it. then in this case, it will first sort according to the second column of the list, and if they are equal, it will sort according to the first column of the list, right?

  • I don’t understand what you mean by ordenar consoante. But your reasoning is right, the past lambda says that the first ordering criterion is the column 1 and the second ordering criterion is the column 0.

  • ok, but the second ordering criterion will only happen if the first criterion is equal right?

  • Exactly. Ordering will only be defined by the second criterion when it cannot be solved by the first.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.