ACx
ACx

Reputation: 71

Python: double sort

Is there a quick and easy way to sort a list of tuples containing two items? (a short list of the tuples I am 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 am trying to sort them first by frequency (largest first), so the number, and then by alphabetical order.

This is what I have so far:

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

This sorts the list by frequency in descending order.

Upvotes: 6

Views: 2797

Answers (2)

hjonasson
hjonasson

Reputation: 140

I would use two sorting functions. One for sorting as you do already. Then sort the results of that by alphabetical order. 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())

Upvotes: 1

Marcin
Marcin

Reputation: 238607

I think I understand what you want to do. Have order of frequencies different than words. For 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)

The result is:

[('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 so called a complex sort. More here. And it works, because sort operations in python are stable. It means that:

when multiple records have the same key, their original order is preserved.

Upvotes: 3

Related Questions