最容易通过例子解释:
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)
是的,我知道我可以写自己的程序,谢谢。
答案 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})