【问题标题】:Most pythonic way of counting on the fly using a loop and dict [duplicate]使用循环和字典动态计数的大多数pythonic方式[重复]
【发布时间】:2016-04-10 16:23:22
【问题描述】:

我经常发现自己使用 dict 来计算某事的发生次数,我想知道是否有一种方法可以在不使用异常的情况下更顺利地完成这项工作。

count_dict = {} 
for file in files:
    ############
    #parse file#
    ############
    for line in lines:
        tokens = line.split()
        if "something" in tokens:
            try:
                count_dict[tokens[0]] += 1
            except KeyError:
                count_dict[tokens[0]] = 1

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    Python 有一个专门用于此的类:collections.Counter

    count_dict = Counter(str.split())
    

    【讨论】:

      猜你喜欢
      • 2018-04-28
      • 2018-03-18
      • 2014-01-23
      • 2014-06-21
      • 2012-09-06
      • 2013-02-06
      • 2017-12-23
      • 2013-12-30
      相关资源
      最近更新 更多