Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counter to List

I have a counter like this :

counter = Counter(['a','a','b','b','b','c'])

which gives this object :

Counter({'b': 3, 'a': 2, 'c': 1})

and from that I want to creat a list such as :

list[0] = 'b'
list[1] = 'a'
list[2] = 'c'

any idea to do that the simpliest and fastest way possible please ? thanks

like image 305
user2741700 Avatar asked Nov 17 '13 04:11

user2741700


1 Answers

You can use collections.Counter.most_common (which returns a list of the n most common elements and their counts from the most common to the least):

>>> counter.most_common()
[('b', 3), ('a', 2), ('c', 1)]

>>> [key for key, _ in counter.most_common()]
['b', 'a', 'c']
like image 107
falsetru Avatar answered Oct 24 '22 00:10

falsetru