average list of dictionaries in python

£可爱£侵袭症+ 提交于 2020-01-06 11:14:24

问题


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


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/29395018/average-list-of-dictionaries-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!