【发布时间】:2017-11-13 05:06:32
【问题描述】:
最简单的例子解释:
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)
是的,我知道我可以编写自己的程序,谢谢。
【问题讨论】:
-
collections.Counter是你的朋友。这个问题太简单了 -
@RomanPerekhrest 这个问题的格式很好而且很清楚,只是因为 OP 没有意识到这一点并不一定使它成为一个坏问题。也就是说,是的,OP 真的应该在谷歌上搜索它。
-
你没有想到要搜索“python counter”吗?
-
@SpencerWieczorek,我在哪里说它不好?这是重复的
-
{e: events.count(e) for e in set(events)}
标签: python dictionary counter