Reputation: 81
I have list like this:
Pasang = [0, 4, 4, 5, 1, 7, 6, 7, 5, 7, 4, 9, 0, 10, 1, 10,...., 23, 9, 23, 7, 23]
I count item from that list:
satuan = Counter(pasang)
then I get :
Counter({5: 10, 6: 7, 0: 5, 1: 5, 7: 5, 10: 4, 11: 4, 15: 4,...,14: 1, 21: 1})
I want to get key from counter, so i do this:
satu = satuan.keys()
and I get sorted list like this:
[0, 1, 2, 4, 5,...,21, 22, 23]
but I need an output like this (not sorted):
[5, 6, 0, 1,...,14, 21]
Sorry for my bad english.
Upvotes: 5
Views: 1068
Reputation: 22954
If you want to maintain the order then have a look at the Counter
object you just created, it has elements sorted w.r.t to the frequency in decreasing order and you can also achieve the same behaviour by sorting the keys on frequency and setting the reverse
flag to be True
import collections
Pasang = [0, 4, 4, 5, 1, 7, 6, 7, 5, 7, 4, 9, 0, 10, 1, 10, 23, 9, 23, 7, 23]
a = collections.Counter(Pasang)
keys = sorted(a.keys(), key = lambda x:a[x], reverse = True)
print a
print keys
>>> Counter({7: 4, 4: 3, 23: 3, 0: 2, 1: 2, 5: 2, 9: 2, 10: 2, 6: 1})
>>> [7, 4, 23, 0, 1, 5, 9, 10, 6]
Upvotes: 0
Reputation: 20015
You probably need:
[key for key, freq in c.most_common()]
where c
is the Counter
instance.
most_common
will return pairs of keys and frequencies, in decreasing order of frequency. Then you extract the key part using a comprehension.
Upvotes: 4