pythonic字典计数器?

时间:2017-06-11 18:31:53

标签: python dictionary counter

最容易通过例子解释:

events = ['foo', 'bar', 'biz', 'foo', 'foo']
events_counter = {}
for event in events:
    if event not in events_counter: # {
        events_counter[event] = 1   # {
    else:                           # {
        events_counter[event] += 1  # {
print events_counter

# {'biz': 1, 'foo': 3, 'bar': 1}

有没有办法以更加pythonic的方式实现突出显示的代码?我觉得应该有一个内置函数,即:

events_counter.count_up(event)

是的,我知道我可以写自己的程序,谢谢。

1 个答案:

答案 0 :(得分:7)

Python有一个内置的Counter数据结构:

from collections import Counter
events = ['foo', 'bar', 'biz', 'foo', 'foo']
cc = Counter(events)
print(cc)

输出:

Counter({'foo': 3, 'bar': 1, 'biz': 1})