【问题标题】:Python- How to find the average of multiple values/key in a dictionaryPython-如何在字典中找到多个值/键的平均值
【发布时间】:2012-12-02 22:19:09
【问题描述】:

我有一本像这样的字典。 . .

CombinedDict = {'Abamectin': [63, 31, 53], 'Difenzoquat metilsulfate': [185, 49, 152], 'Chlorpyrifos': [14, 26, 56], 'Dibutyl phthalate': [25, -17, -18] 

等等。我总共有 48 个不同的键。

我想要得到的是三个数字的平均值。所以我会得到一个看起来像这样的字典。 . .

  AvgDictName = {'Abamectin': [49], 'Difenzoquat metilsulfate': [128], 'Chlorpyrifos': [32], 'Dibutyl phthalate': [-3] . . . 

我试过用这条线

    AvgDictName = dict([(key, float(sum([int(i) for i in values])) / len(values)) for key, values in CombinedDict])

但是我得到太多的值来解压错误 有任何想法吗?我认为也可以通过将 dict 放入列表并使用 len 和 sum 命令从列表中找到平均值然后转换回 dict 来完成,但我真的不知道该怎么做。谢谢,我觉得这应该很容易。

【问题讨论】:

    标签: python dictionary average


    【解决方案1】:

    如果你想解压成key, values,你需要遍历CombinedDict.items()CombinedDict.iteritems()

    【讨论】:

    • .iteritems() 用于 python 2.x
    • @inspectorG4dget, .items() 实际上更好,因为它是“Python 3 证明”,除非您真的需要针对大值列表进行优化。
    • @BenHoyt:这就是 2to3 工具的用途。我是否也应该将所有打印语句都用括号括起来?
    • @Eric: 如果你使用from __future__ import print_function :P(抱歉,你选错了例子)
    【解决方案2】:

    for x in dictionary: ... 遍历字典的键。

    除非键本身是元组,否则for a, b in dictionary 会出错,因为它会尝试将键解包为两个值。

    对于迭代字典,您应该使用items()keys()values()(或它们在python 2.x 中的iter* 等效项)

    【讨论】:

      【解决方案3】:
          python 3.2
      
          >>> [(i,sum(v)//len(v)) for i,v in t.items()]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多