4

对于这个函数,我想计算每个元素的出现次数并返回一个字典。如: [a,b,a,c,b,a,c] 并返回 {a:3,b:2,c:2} 怎么做?

4

3 回答 3

6

您可以使用Counter

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

DefaultDict

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

或者:

def get_cnt(lVals):
    d = dict(zip(lVals, [0]*len(lVals)))
    for x in lVals:
        d[x] += 1
    return d   
于 2012-11-16T03:23:39.313 回答
1

使用内置类Counter

import collections
collections.Counter(['a','a','b'])
于 2012-11-16T03:24:51.153 回答
1

你可以使用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}

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}
于 2012-11-16T03:36:09.700 回答