2015-03-13 37 views
5

我有字典列表。假設它從字典列表中獲取平均值

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) 

但是現在我需要從它得到平均值。怎麼做?

回答

13

只需通過列表的長度除以值的總和:

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) 
+0

我加了備註浮動結果。 – catavaran 2015-03-13 08:49:21

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

catavaran的anwser更容易,你並不需要一個lambda