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

标签 python dictionary key

我经常编写简短的程序,在运行时收集统计数据并在最后报告。我通常将这些统计数据收集在字典中并在最后显示。

我最终像下面的简单示例一样编写了这些内容,但我希望有一种更干净、更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

最佳答案

您可以组合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})})

关于python - 使用 python 字典保存程序统计信息的干净方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641229/

相关文章:

python - 使用 Gibbs 采样器进行基序搜索

python - 开发神经网络时如何在python中使用sigmoid函数

netbeans - NetBeans 8 字典位于哪里?

Android Facebook 开发人员无法在 "Save Changes"上为 "Sample App Settings"设置 "Android Key Hash"

json - 如何使用 jq 查找某个键的所有路径

python - 如何更改列表中字典中的字符串键| python3.6

python - 将图像列表转换为一个视频时在FFmpeg中设置图像持续时间?

python - 在 Flask-Celery 中收到类型为 ""的未注册任务

javascript - 如何在本地存储(或其他地方)中保存 ES6 map ?

c# - 为什么字典不像哈希表那样访问不存在的键?