给列表里的元素计数

例如有个这样的列表

data = [1,2,5,3,1,3,6,3,4,8,9]

我们想对列表里的元素进行计数,返回一个字典,元素为键,计数为值。

方法一

mydict = {}
for e in data:
    if mydict.has_key(e):
        mydict[e] += 1
    else:
        mydict[e] = 1
print mydict
# {1: 2, 2: 1, 3: 3, 4: 1, 5: 1, 6: 1, 8: 1, 9: 1}

方法二

mydict = {}
for e in data:
    mydict[e] = mydict.get(e, 0)  + 1
print mydict

方法三

from collections import defaultdict
mydict = defaultdict(int)
for e in data:
    mydict[e] += 1
print mydict
# defaultdict(<type 'int'>, {1: 2, 2: 1, 3: 3, 4: 1, 5: 1, 6: 1, 8: 1, 9: 1})
print dict(mydict)
# {1: 2, 2: 1, 3: 3, 4: 1, 5: 1, 6: 1, 8: 1, 9: 1}

方法四

from collections import Counter
c = Counter(data)
print c
# Counter({3: 3, 1: 2, 2: 1, 4: 1, 5: 1, 6: 1, 8: 1, 9: 1})
print dict(c)
# {1: 2, 2: 1, 3: 3, 4: 1, 5: 1, 6: 1, 8: 1, 9: 1}

results matching ""

    No results matching ""