在python中缩短更新字典的代码

Shorting the code for update dictionary in python

本问题已经有最佳答案,请猛点这里访问。

如果数组中的某个元素并将其存储在字典中,是否有一个较短版本的当前代码用于计算出现次数?

1
2
3
4
5
6
7
8
9
a = [1,2,2,3,4,5,2,2,1]
dic = {}
for x in a:
    if x in dic:
        dic[x] = dic[x] + 1
    else:
        dic[x] = 1

print dic


是的

您可以使用dictionary.get(key, default)获取键的值,如果键不存在,它将给出默认参数。

1
2
3
4
5
a = [1,2,2,3,4,5,2,2,1]
dic = {}

for n in a:
    dic[n] = dic.get(n, 0) + 1


您可以使用collections.Counter()

1
2
3
4
from collections import Counter

a = [1, 2, 2, 3, 4, 5, 2, 2, 1]
dic = Counter(a)

从文档中:

A Counter is a dict subclass for counting hashable objects. It is an
unordered collection where elements are stored as dictionary keys and
their counts are stored as dictionary values.