从字典列表中获取平均值

Get average value from list of dictionary

我有字典列表。说吧

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)

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

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

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

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

print float(sum(d['value'] for d in total)) / len(total)
reduce(lambda x, y: x + y, [d['value'] for d in total]) / len(total)

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

我需要对同一事物进行更通用的实现才能在整个词典上工作。所以这是一个简单的选择:

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}

如果值是数字列表,则对 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