Like the title says I need to write a function that will sort a list by frequency of letters. Normally I would supply my code with what I have so far but I have no idea where to get started. I'm sure its something simple but I just don't know what to do. I need them sorted in decreasing order, any help is appreciated, thanks.
For Python2.7+, use a collections.Counter and its most_common method:
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
For Python2.6 or lower, you can use the equivalent Counter recipe.
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})
as per Sorted Word frequency count using python
if you need letters instead of words you can go like this:
>>> 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With