jianjun
jianjun

Reputation: 93

what's the pythonic way to count the occurrence of an element in a list?

this is what I did. is there a better way in python?

for k in a_list:   
  if kvMap.has_key(k):
    kvMap[k]=kvMap[k]+1   
  else:
    kvMap[k]=1

Thanks

Upvotes: 9

Views: 3836

Answers (6)

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

Such an old question, but considering that adding to a defaultdict(int) is such a common use, It should come as no surprise that collections has a special name for that (since Python 2.7)

>>> from collections import Counter
>>> Counter([1, 2, 1, 1, 3, 2, 3, 4])
Counter({1: 3, 2: 2, 3: 2, 4: 1})
>>> Counter("banana")
Counter({'a': 3, 'n': 2, 'b': 1})

Upvotes: 6

John Novatnack
John Novatnack

Reputation: 131

Single element:

a_list.count(k)

All elements:

counts = dict((k, a_list.count(k)) for k in set(a_list))

Upvotes: 9

runeh
runeh

Reputation: 3887

If your list is sorted, an alternative way would be to use itertools.groupby. This might not be the most effective way, but it's interesting nonetheless. It retuns a dict of item > count :

>>> import itertools
>>> l = [1,1,2,3,4,4,4,5,5,6,6,6,7]
>>> dict([(key, len([e for e in group]))
          for (key, group)
          in itertools.groupby(l)])
{1: 2, 2: 1, 3: 1, 4: 3, 5: 2, 6: 3, 7: 1}

Upvotes: 1

Brian Clapper
Brian Clapper

Reputation: 26211

Another solution exploits setdefault():

for k in a_list:
    kvMap[k] = kvMap.setdefault(k, 0) + 1

Upvotes: 3

S.Lott
S.Lott

Reputation: 391854

Use defaultdict

from collections import defaultdict
kvmap= defaultdict(int)
for k in a_list:
    kvmap[k] += 1

Upvotes: 16

Dana
Dana

Reputation: 32957

I dunno, it basically looks fine to me. Your code is simple and easy to read which is an important part of what I consider pythonic.

You could trim it up a bit like so:

for k in a_list:
     kvMap[k] = 1 + kvMap.get(k,0)

Upvotes: 7

Related Questions