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 |
是的
您可以使用
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 |
号
您可以使用
1 2 3 4 | from collections import Counter a = [1, 2, 2, 3, 4, 5, 2, 2, 1] dic = Counter(a) |
从文档中:
A
Counter is adict 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.
号