我经常编写简短的程序,在运行时收集统计数据并在最后报告。我通常将这些统计数据收集在字典中并在最后显示。
我最终像下面的简单示例一样编写了这些内容,但我希望有一种更干净、更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
最佳答案
您可以组合defaultdict
与 Counter
这会将 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})})
关于python - 使用 python 字典保存程序统计信息的干净方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641229/