count elements in list !

Some times, I want to count elements in list object.
Elements are words, smiles;-), and any more.
When I did it, I made dictionary that has keys in each elements and count it.
Like follow..

listobj = list("aabcabbccc")
dict = {}
for i in listobj:
    if dict.has_key(i):
        dict[i] += 1
    else:
       dict[i] = 1

But Today, I knew more efficient method, “collections”.
I feel more better.

form collections import Counter
listobj = list("aabcabbccc")
collection = Counter( listobj )
for key, val in collection.most_common():
    print key, val

Then I could get

c 4
a 3
b 3

That’s nice !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s