使用python字典保存程序统计信息的干净方法

2024-03-29 09:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我经常在收集统计数据时编写简短的程序,然后在最后报告。我通常将这些数据收集到字典中,并在最后显示出来。你知道吗

最后我像下面这个简单的例子一样写了这些,但我希望有一个更干净更具Python风格的方法来做到这一点。当存在多个度量时,这种方法可能会变得相当大(或嵌套)。你知道吗

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

Tags: 数据方法namein程序if字典stats
2条回答

您可以将^{}^{}组合起来,这将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})})

如果你只需要数数func_namesresults,就用Counter

import collections
stats = collections.Counter()

def add_result_to_stats(result,func_name):
    stats.update({(func_name, result):1})

相关问题 更多 >