Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 794
jianjun Avatar asked Jan 09 '09 19:01

jianjun


4 Answers

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})
like image 192
SingleNegationElimination Avatar answered Oct 17 '22 12:10

SingleNegationElimination


Use defaultdict

from collections import defaultdict
kvmap= defaultdict(int)
for k in a_list:
    kvmap[k] += 1
like image 20
S.Lott Avatar answered Oct 17 '22 14:10

S.Lott


Single element:

a_list.count(k)

All elements:

counts = dict((k, a_list.count(k)) for k in set(a_list))
like image 33
John Novatnack Avatar answered Oct 17 '22 14:10

John Novatnack


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)
like image 38
Dana Avatar answered Oct 17 '22 12:10

Dana