我需要能计算字典中权重的平均值。这也需要是一个函数。这是我的密码animal=dict()
animal['1']={'ID': '21012', 'plot':4, 'year':'1993', 'species': 'DM', 'weight': 42, 'hindfoot': 36, 'tag':'1EA0F9'}
animal['2']={'ID':'22012', 'plot':4, 'year':'1995', 'species': 'DM', 'weight': 31, 'hindfoot': 37, 'tag':'0D373C'}
animal['3']={'ID': '23012', 'plot':17, 'year':'1996', 'species': 'DM', 'weight': 25, 'hindfoot': 37, 'tag':'64C6CC'}
animal['4']={'ID': '24012','plot':21, 'year':'1996', 'species': 'PP', 'weight': 26, 'hindfoot': 22, 'tag':'1F511A'}
animal['5']={'ID': '25012', 'plot':22, 'year':'1997', 'species': 'DM', 'weight': 53, 'hindfoot': 35, 'tag':'2624'}
animal['6']={'ID': '26012', 'plot':17, 'year':'1997', 'species': 'OT', 'weight': 14, 'hindfoot': 18, 'tag':'2863'}
animal['7']={'ID': '27012', 'plot':18, 'year':'1997', 'species': 'OT', 'weight': 23, 'hindfoot': 21, 'tag':'2913'}
animal['8']={'ID': '28012', 'plot':13, 'year':'1998', 'species': 'OT', 'weight': 36, 'hindfoot': 19, 'tag':'2997'}
animal['9']={'ID': '29012', 'plot':6, 'year':'1999', 'species': 'PM', 'weight': 20, 'hindfoot': 20, 'tag':'406'}
animal['10']={'ID': '30000', 'plot':14, 'year':'2000', 'species': 'DM', 'weight': 41, 'hindfoot': 34, 'tag':'156'}
result=dict()
def calc_avg(r):
if all(isinstance(x, numbers.Number) for x in r["weight"]):
print a["title"],":", sum(r["weight"])/float(len(r["weight"]))
return
import numbers
calc_avg(animal.items)