Reputation: 901
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
Upvotes: 13
Views: 22534
Reputation: 103754
You could do this:
from collections import Counter
import operator
counter = Counter(['a','a','b','b','b','c'])
print [k for k,v in sorted(counter.iteritems(), key=operator.itemgetter(1), reverse=True)]
# ['b', 'a', 'c']
Or, better still:
from collections import Counter
counter = Counter(['a','a','b','b','b','c'])
print [k for k,v in counter.most_common()]
Upvotes: 0
Reputation: 368954
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']
Upvotes: 16
Reputation: 13372
Simplest (IMO) method as told by falsetru
sorted(counter, key=counter.get, reverse=True)
The above would sort the counter dict
based on the values of the keys (.get()
) & return a reversed list
.
Upvotes: 5
Reputation: 7806
if you want to skip the steps you can type.
list(set(['a','a','b','b','b','c']))
Upvotes: 0
Reputation: 34146
You can cast it to a list, but it will not keep the order you want since dictionaries are unsorted:
list1 = list(counter)
Upvotes: 3