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

4

I'm using sorted to organize a list, however I need two criteria to organize it for tie cases, so I call sorted( ) twice. Can you do this organization by calling sorted( ) only once?

Basically, the code is as follows:

lista_intermediaria = sorted(minha_lista, key = funcao_comparacao_1)
lista_organizada = sorted(lista_intermediaria, key = funcao_comparacao_2)
    
asked by anonymous 01.07.2015 / 03:52

1 answer

4

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

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 the same - then they will be compared by criterion 1 (note: I put 2 before 1 to be consistent with what you are doing) p>     

01.07.2015 / 03:58