【问题标题】:Clean way of using a python dictionary to hold program statistics使用 python 字典保存程序统计信息的简洁方法
【发布时间】:2016-04-15 07:48:02
【问题描述】:

我经常写一些小程序来收集统计数据,然后在最后运行和报告。我通常将这些统计数据收集在字典中以显示在最后。

我最终会像下面的简单示例一样编写这些,但我希望有一种更简洁、更 Pythonic 的方式来执行此操作。当有多个指标时,这种方式可能会变得非常大(或嵌套)。

stats = {} 

def add_result_to_stats(result,func_name):
    if not func_name in stats.keys():
        stats[func_name] = {}
    if not result in stats[func_name].keys():
        stats[func_name][result] = 1
    else:
        stats[func_name][result] += 1

【问题讨论】:

    标签: python dictionary key


    【解决方案1】:

    您可以将defaultdictCounter 结合起来,这会将add_result_to_stats 减少为一行:

    from collections import defaultdict, Counter
    stats = defaultdict(Counter)
    
    def add_result_to_stats(result, func_name):
        stats[func_name][result] += 1
    
    add_result_to_stats('foo', 'bar')
    print stats # defaultdict(<class 'collections.Counter'>, {'bar': Counter({'foo': 1})})
    

    【讨论】:

    • 我更喜欢这个答案,因为它的打印能力
    【解决方案2】:

    如果您只需要计算func_namesresults,请选择Counter

    import collections
    stats = collections.Counter()
    
    def add_result_to_stats(result,func_name):
        stats.update({(func_name, result):1})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      相关资源
      最近更新 更多