【问题标题】:pythonic dictionary counter? [duplicate]python字典计数? [复制]
【发布时间】: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


【解决方案1】:

Python为此内置了Counter数据结构:

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

输出:

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

【讨论】:

  • ahaha 抱歉,我确实看过收藏品但一定错过了。
猜你喜欢
  • 2016-02-04
  • 1970-01-01
  • 2017-04-19
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
相关资源
最近更新 更多