Reputation: 427
I'm using the Python collections library to print out the most common character in a string and how many times it's repeated.
import collections
results = collections.Counter("this is fun")
listresults= results.most_common()
print listresults
this is what my result is :
[(' ', 2), ('i', 2), ('s', 2), ('f', 1), ('h', 1), ('n', 1), ('u', 1), ('t', 1)]
which is not what I want. I want something like
[(2,"i") (2, " "),...]
does anyone know how to produce the desired result?
Upvotes: 1
Views: 605
Reputation: 441
Another slightly less readable but still quite pythonic way:
import collections
results = collections.Counter("this is fun")
listresults= results.most_common()
print listresults
print zip(*reversed(zip(*listresults)))
Upvotes: 0
Reputation: 11591
You could try this:
>>> from collections import Counter
>>> results = Counter("this is fun")
>>> r = results.most_common()
>>> what_i_want = [(y, x) for x, y in r]
>>> what_i_want
[(2, ' '), (2, 'i'), (2, 's'), (1, 'f'), (1, 'h'), (1, 'n'), (1, 'u'), (1, 't')]
I use a list comprehension because list comprehensions are often more efficient than using for
clauses and take up far less space. Per your comment below, though, a for
clause would look like what jamylak has suggested:
>>> what_i_want = []
>>> for x, y in r:
what_i_want.append((y, x))
>>> what_i_want
[(2, ' '), (2, 'i'), (2, 's'), (1, 'f'), (1, 'h'), (1, 'n'), (1, 'u'), (1, 't')]
Upvotes: 4