使用字典理解规范化概率

问题描述

我的python字典看起来像

probabilities = {'harry': {'gene': {0: 0.23,1: 0.09,2: 0.13},'trait': {False: 0.23,True: 0.32}},'jim': {'gene': {0: 0.12,1: 0.15,2: 0.56},'trait': {False: 0.67,True: 0.12}}}

我通过编写类似的代码来对其进行规范化

for person in probabilities:
        for attribute in probabilities[person]:
            denominator = sum(probabilities[person][attribute].values())
            for value in probabilities[person][attribute]:
                probabilities[person][attribute][value] /= denominator

代码很好,因为它可以完美地标准化概率。但是我可以使用字典理解来做同样的事情吗?如果是这样,怎么办?如果没有,为什么?

解决方法

一点点的努力就带给我:

probabilities = {'harry': {'gene': {0: 0.23,1: 0.09,2: 0.13},'trait': {False: 0.23,True: 0.32}},'jim': {'gene': {0: 0.12,1: 0.15,2: 0.56},'trait': {False: 0.67,True: 0.12}}}

probabilities_new = {
    p: {
        k: {
            k_inn: v_inn / sum(v.values())
            for k_inn,v_inn in v.items()
        }
        for k,v in a.items()
    }
    for p,a in probabilities.items()
}