Reputation: 193
I have a counter with the following information:
Counter({'red': 3, 'blue': 2, 'green': 1})
and I wish to convert it to a list, ordered from least to greatest number of frequency like this:
list = ['green', 'blue', 'red']
Every time I iterate over the counter, it seems to put it into a list sorted in alphabetical order. Is there an easy way to get it to be sorted how I want it?
Upvotes: 2
Views: 79
Reputation: 13869
Counter.most_common
with no arguments returns a list of tuples of the items and their counts sorted in descending order by count. Python's built-in reversed
returns an iterator which traverses a sequence in reverse order.
Combine all that with a list comprehension to ignore the counts, and you have your solution.
from collections import Counter
counter = Counter({'red': 3, 'blue': 2, 'green': 1})
sorted_items = [item for item, _ in reversed(counter.most_common())]
Upvotes: 2
Reputation: 77069
You just need a key function:
sorted(yourcounter, key=lambda i: yourcounter[i])
They key just needs to output an inherently orderable result. Most of the time your best bet is if it returns an integer. For example, you can reverse the result just by making it negative.
sorted(yourcounter, key=lambda i: -yourcounter[i])
In this case you can also write the original slightly more tersely as
sorted(yourcounter, key=yourcounter.get)
Upvotes: 2