Organize list with more than one criterion in case of a tie

Asked

Viewed 344 times

4

I’m using sorted to organize a list, but I need two criteria to organize it for tie cases, for this, I call sorted( ) twice. It has how to make this organization calling sorted( ) only once?

Basically, so that’s the code:

lista_intermediaria = sorted(minha_lista, key = funcao_comparacao_1)
lista_organizada = sorted(lista_intermediaria, key = funcao_comparacao_2)

1 answer

5


Assuming the comparison functions are not overly expensive, what you can do is return a tuple with the result of the first function in position 0 and the result of the second position 1:

lista_organizada = sorted(minha_lista, key=lambda x:
    (funcao_comparacao_2(x), funcao_comparacao_1(x)))

So, first the elements will be compared by criterion 2 and - if the result is equal - then they will be compared by criterion 1 (note: I put 2 before 1 to be consistent with what you are doing).

Browser other questions tagged

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