Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list by frequency of letter in python (decreasing order)

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.

like image 207
Neemaximo Avatar asked Nov 01 '11 01:11

Neemaximo


2 Answers

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.

like image 32
unutbu Avatar answered Oct 03 '22 07:10

unutbu


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)
like image 181
robert king Avatar answered Oct 03 '22 06:10

robert king