Python: double sorting

Is there a quick and easy way to sort a list of tuples containing two elements? (short list of tuples I'm trying to sort:

[('this', 4), ('in', 4), ('dedicated', 4), ('who', 3), ('us', 3), ('they', 3), ('so', 3), ('shall', 3), ('people', 3), ('is', 3), ('great', 3), ('dead', 3), ('are', 3), ('It', 3), ('which', 2), ('what', 2)] 

I try to sort them first by frequency (by the size of the first), so the number, and then alphabetically.

This is what I have so far:

 word_list.sort(key=itemgetter(1,0), reverse = True) 

Sorts the list by frequency in descending order.

+6
source share
2 answers

I think I understand what you want to do. You have a different frequency order than words. To do this, you need to sort twice:

 from operator import itemgetter word_list = [('this', 4), ('in', 4), ('dedicated', 4), ('who', 3), ('us', 3), ('they', 3), ('so', 3), ('shall', 3), ('people', 3), ('is', 3), ('great', 3), ('dead', 3), ('are', 3), ('It', 3), ('which', 2), ('what', 2)] #first we set words in alphabetical order word_list2 = sorted(word_list, key=lambda l: l[0].lower()) # then we sort them by frequency word_list2 = sorted(word_list2, key=itemgetter(1), reverse = True) print(word_list2) 

Result:

 [('dedicated', 4), ('in', 4), ('this', 4), ('are', 3), ('dead', 3), ('great', 3), ('is', 3), ('It', 3), ('people', 3), ('shall', 3), ('so', 3), ('they', 3), ('us', 3), ('who', 3), ('what', 2), ('which', 2)] 

This is the so-called complex view. More details here . And this works because the sort operations in python are stable. It means that:

when several records have the same key, their original order is saved.

+3
source

I would use two sorting functions. One to sort, like you. Then sort the results of this alphabetically. Does that make sense to you?

 word_list = [('this', 4), ('in', 4), ('dedicated', 4), ('who', 3), ('us', 3), ('they', 3), ('so', 3), ('shall', 3), ('people', 3), ('is', 3), ('great', 3), ('dead', 3), ('are', 3), ('It', 3), ('which', 2), ('what', 2)] word_list.sort(key=lambda i:i[1], reverse = True) word_list.sort(key=lambda i:i[0].lower()) 
+1
source

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


All Articles