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
       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 !


Published by iwatobipen

I'm medicinal chemist in mid size of pharmaceutical company. I love chemoinfo, cording, organic synthesis, my family.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: