Sorting Tuples In Python Based On Their Values
I am trying to print the top 10 frequent words using the following code. However, its not working. Any idea on how to fix it? def reducer_count_words(self, word, counts): # sen
Solution 1:
Use collections.Counter
and its most_common
method:
>>>from collections importCounter
>>>my_words = 'a a foo bar foo'
>>>Counter(my_words.split()).most_common()
[('foo', 2), ('a', 2), ('b', 1)]
Solution 2:
Example:
most_common([n])
Return a list of the n most common elements and their counts from the most common to the least. If n isnot specified, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:
>>> from collections import Counter
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
Solution 3:
tmp = sorted(word_count_pairs, key=lambda pair: pair[0], reverse=True)[0:10]
Explanation:
- The
key
parameter ofsorted()
allows you to run a function on each element before comparison. lambda pair: pair[0]
is a function that extracts the number from your word_count_pairs.reverse
sorts in descending order, instead of ascending order.
Sources:
- https://wiki.python.org/moin/HowTo/Sorting#Key_Functions
- https://docs.python.org/2/library/functions.html#sorted
aside: If you have many different words, sorting the entire list to find the top ten is inefficient. There are much more efficient algorithms. The most_common()
method mentioned in another answers probably utilizes a more efficient algorithm.
Post a Comment for "Sorting Tuples In Python Based On Their Values"