简体   繁体   English

python中字典的平均列表

[英]average list of dictionaries in python

I have a list of dictionary like this 我有这样的字典清单

data = [{'Name': 'john', 'Height': 176, 'Weight':62, 'IQ':120,..},...]

the .. signifies various other integer/float attributes and all elements of the list has same format.. ..表示其他各种整数/浮点属性,列表的所有元素都具有相同的格式。

I want to get the average Height, Weight and all other numerical attributes in the cleanest/easiest way. 我想以最干净/最简单的方式获取平均身高,体重和所有其他数值属性。

I could not come up with a better way than normal for looping which was too messy... and i don't want to use any external packages 我无法提出比正常情况更好的循环方法,这太混乱了……而且我不想使用任何外部软件包

Yeah there really isn't a better way than looping. 是的,确实没有比循环更好的方法了。 Your basic issue is you have to look at each element in the list, you can't really do that without looping. 您的基本问题是必须查看列表中的每个元素,如果没有循环就不能真正做到这一点。

Here is a start for you 这是您的起点

>>> data = [{'Name': 'john', 'Height': 176},{'Name': 'Vikash', 'Height': 170}]
>>> vals = [i['Height'] for i in data]
>>> sum(vals)/len(vals)
173

Likewise you can have a different loop for each attribute or put the loop in a function 同样,您可以为每个属性设置不同的循环,也可以将循环放入函数中

>>> def avrg(data,s):
...     vals = [i[s] for i in data]
...     return sum(vals)/len(vals)
... 
>>> data = [{'Name': 'john', 'Height': 176, 'Weight':62, 'IQ':120,},{'Name': 'Vikash', 'Height': 170, 'Weight':68, 'IQ':100}]
>>> 
>>> avrg(data,'Weight')
65

You can use the following 您可以使用以下内容

sum([item['Weight'] for item in data])/len(data)

and use 和使用

float(len(data)) 

if you want a more exact value. 如果您想要更精确的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM