Complex sorting with multiple parameters?

I have a list of tuples:

li = [('fink', 3), ('flip', 3), ('flock', 4), ('foo', 12), ('foot', 20), ('football', 20), ('futz', 10), ('flip', 3), ('flank', 3), ('flop', 3)] 

How can I sort the list by descent numbers first, and then alphabetically descend? Results:

 ('foot', 20) ('football', 20) ('foo', 12) ('futz', 10) ('flock', 4) ('fink', 3) ('flip', 3) ('flake', 3) ('flop', 3) from operator import itemgetter sorted_li = sorted(li, key=itemgetter(1,0), reverse=True) 

While the above code is sorted in descending order, correctly, words are not sorted in alphabetical order.

+6
source share
3 answers

This is too complicated for a single itemgetter . Use lambda instead:

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

This is about the same speed as two consecutive sorts using an itemgetter , but it is smaller than the code and probably more readable.

+9
source

Since Python sorting is stable, it's easiest to sort twice:

 sorted_li = sorted(li, key=itemgetter(1), reverse=True) sorted_li.sort(key=itemgetter(0)) 
+6
source

Since Python sorting is stable, it is easiest to sort it twice:

 sorted_li = sorted(li, key=itemgetter(0)) sorted_li.sort(key=itemgetter(1), reverse=True) 

but note that you must first use your order with the lowest priority, and then the rest should be based on priority. highest priority should be last. this is the most important thing you should consider when trying to use the Sorted function.

0
source

Source: https://habr.com/ru/post/920308/


All Articles