from collections import Counter
histogram = Counter()
...
histogram[n] += 1
对于数字以外的值,请查看collections.defaultdict。在本例中,您可以使用defaultdict(int)代替Counter,但是Counter添加了.elements()和{}等功能。defaultdict(list)是另一个非常有用的例子。在
Counter还有一个方便的构造函数。而不是:
^{pr2}$
你只需:histogram = Counter(nums)
其他选项:histogram.setdefault(n, 0)
histogram[n] += 1
以及histogram[n] = histogram.get(n, 0) + 1
在列表的情况下,setdefault可能更有用,因为它返回值,即:dict_of_lists.setdefault(key, []).append(value)
最后一个好处是,现在稍微偏离轨道,下面是我最常用的defaultdict:def group_by_key_func(iterable, key_func):
"""
Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements
of the iterable and the values are lists of elements all of which correspond to the key.
>>> dict(group_by_key_func("a bb ccc d ee fff".split(), len)) # the dict() is just for looks
{1: ['a', 'd'], 2: ['bb', 'ee'], 3: ['ccc', 'fff']}
>>> dict(group_by_key_func([-1, 0, 1, 3, 6, 8, 9, 2], lambda x: x % 2))
{0: [0, 6, 8, 2], 1: [-1, 1, 3, 9]}
"""
result = defaultdict(list)
for item in iterable:
result[key_func(item)].append(item)
return result