Count every item in a list without .count

For this function, I want to count the occurrences of each element and return a dict. such as: [a, b, a, c, b, a, c] and return {a: 3, b: 2, c: 2} How to do this?

+4
source share
3 answers

You can use Counter and then:

from collections import Counter Counter( ['a','b','a','c','b','a','c'] ) 

Or DefaultDict :

 from collections import defaultdict d = defaultdict(int) for x in lVals: d[x] += 1 

OR

 def get_cnt(lVals): d = dict(zip(lVals, [0]*len(lVals))) for x in lVals: d[x] += 1 return d 
+6
source

Use the built-in class Counter

 import collections collections.Counter(['a','a','b']) 
+1
source

you can use dict.setdefault :

 In [4]: def my_counter(lis): dic={} for x in lis: dic[x]=dic.setdefault(x,0)+1 return dic ...: In [5]: my_counter(['a','b','a','c','b','a','c']) Out[5]: {'a': 3, 'b': 2, 'c': 2} 

or dict.get :

 In [10]: def my_counter(lis): dic={} for x in lis: dic[x]=dic.get(x,0)+1 return dic ....: In [11]: my_counter(['a','b','a','c','b','a','c']) Out[11]: {'a': 3, 'b': 2, 'c': 2} 
+1
source

Source: https://habr.com/ru/post/1446369/


All Articles