【问题标题】:Get average value from list of dictionary从字典列表中获取平均值
【发布时间】:2015-03-13 08:31:20
【问题描述】:

我有字典列表。说吧

total = [{"date": "2014-03-01", "value": 200}, {"date": "2014-03-02", "value": 100}{"date": "2014-03-03", "value": 400}]

我需要从中获取最大值、最小值、平均值。我可以使用以下代码获取最大值和最小值:

print min(d['value'] for d in total)
print max(d['value'] for d in total)

但现在我需要从中获取平均值。怎么做?

【问题讨论】:

    标签: python list dictionary average


    【解决方案1】:

    只需将值的总和除以列表的长度即可:

    print sum(d['value'] for d in total) / len(total)
    

    请注意,整数除法返回整数值。这意味着[5, 5, 0, 0] 的平均值将是2 而不是2.5。如果您需要更精确的结果,则可以使用 float() 值:

    print float(sum(d['value'] for d in total)) / len(total)
    

    【讨论】:

    • 我添加了关于浮动结果的注释。
    【解决方案2】:

    我需要一个更通用的实现相同的东西来处理整个字典。所以这是一个简单的选择:

    def dict_mean(dict_list):
        mean_dict = {}
        for key in dict_list[0].keys():
            mean_dict[key] = sum(d[key] for d in dict_list) / len(dict_list)
        return mean_dict
    

    测试:

    dicts = [{"X": 5, "value": 200}, {"X": -2, "value": 100}, {"X": 3, "value": 400}]
    dict_mean(dicts)
    {'X': 2.0, 'value': 233.33333333333334}
    

    【讨论】:

      【解决方案3】:
      reduce(lambda x, y: x + y, [d['value'] for d in total]) / len(total)
      

      catavaran 的 anwser 更简单,你不需要 lambda

      【讨论】:

        【解决方案4】:

        如果值是数字列表,则改进 dsalaj 的答案:

        def dict_mean(dict_list):
            mean_dict = {}
            for key in dict_list[0].keys():
                mean_dict[key] = np.mean([d[key] for d in dict_list], axis=0)
            return mean_dict
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-13
          • 2018-02-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多