Sorting a list by letter frequency in python (descending order)

As in the title, I need to write a function that will sort the list by letter frequency. Normally I would put my code on what I have, but I have no idea where to start. I’m sure this is something simple, but I just don’t know what to do. I need them sorted in descending order, any help is appreciated, thanks.

+5
source share
2 answers

in python 2.7 or higher you can use a counter: http://docs.python.org/dev/library/collections.html#collections.Counter

>>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
>>> cnt = Counter(mywords)
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

according to Sort word frequency using python

, :

>>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
>>> myletters=list("".join(mywords))
>>> myletters
['r', 'e', 'd', 'b', 'l', 'u', 'e', 'r', 'e', 'd', 'g', 'r', 'e', 'e', 'n', 'b', 'l', 'u', 'e', 'b', 'l', 'u', 'e']
>>> Counter(myletters)
+9

Python2.7 + collections.Counter most_common:

import collections

text='abccccabcbb'
count=collections.Counter(text)

print(count.most_common())
# [('c', 5), ('b', 4), ('a', 2)]

print(''.join(letter*freq for letter,freq in count.most_common()))
# cccccbbbbaa

Python2.6 Counter.

+4

All Articles