Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count each element in list without .count

Tags:

python

list

count

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

like image 532
user1813564 Avatar asked Feb 19 '23 11:02

user1813564


1 Answers

You can use Counter 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   
like image 129
Artsiom Rudzenka Avatar answered Feb 21 '23 00:02

Artsiom Rudzenka