Sorted function in python

I wrote a program that should sort the following:

unsorted_list=[['le', 5], ['aab', 4], ['aaa', 5]] 

in

 [['aaa', 5], ['le', 5], ['aab', 4]] 

It must be sorted by number. If the numbers match, then they must be sorted in alphabetical order. I have the following code:

 def sortItem(lista): ''' func for sort by item''' return lista[1] sorted(unsorted_list, key=sortItem, reverse=True) 

Unfortunately, it does not return a string in alphabetical order. Any suggestion how to do this?

+6
source share
3 answers

Since x[1] is an integer, you can sort it from maximum to minimum by simply negating it:

 sorted(unsorted_list, key=lambda x: (-x[1], x[0])) 

Tuples created in key will be sorted according to the first element ( -x[1] ) and then the second element ( x[0] ). This exactly matches your logic:

"So this means that it is sorted by number, but if the numbers are the same, the sorting will be in alphabetical form."

+10
source
 In [2]: l = [['le', 5], ['aab', 4], ['aaa', 5]] In [3]: sorted(l, key=lambda (x,y):(-y,x)) Out[3]: [['aaa', 5], ['le', 5], ['aab', 4]] 
+6
source

If someone is not familiar with the lambda function, here's how to parse it by defining your own function from scratch -

 unsorted_list=[['le', 5], ['aab', 4], ['aaa', 5]] def num_and_alpha(tuple): return (-tuple[1], tuple[0]) print sorted(unsorted_list, key=num_and_alpha) 
0
source

All Articles