我有3个词典:
zosia = {'imie': 'Zosia', 'zadania': 1, 'quizy': 2, 'testy': 5 },
jas = {'imie': 'Jas', 'zadania': 5, 'quizy': 5, 'testy': 5 },
malgosia = {'imie': 'Malgosia', 'zadania': 3, 'quizy': 3, 'testy': 4 }
包含它们的列表:
studenci = [zosia, jas, malgosia]
我需要在studenci列表中包含的所有词典中创建一个平均值(' zadania'' quizy' testy')的函数。所以基本上我需要平均studenci。提前谢谢。
答案 0 :(得分:2)
只需将值链接起来,然后使用sum()
和len()
对其进行平均。请注意,您的问题中的词语后面不能有逗号;将它们包装成元组。
from __future__ import division # only use this if you are in python 2.7
from itertools import chain
zosia = {'imie': 'Zosia', 'zadania': 1, 'quizy': 2, 'testy': 5 }
jas = {'imie': 'Jas', 'zadania': 5, 'quizy': 5, 'testy': 5 }
malgosia = {'imie': 'Malgosia', 'zadania': 3, 'quizy': 3, 'testy': 4 }
studenci = [zosia, jas, malgosia]
def get_average(dicts, values_labels): # you need to specify which members of zosia, jas, malgosia, etc. you want to count
values = list(chain.from_iterable((D[label] for label in values_labels) for D in dicts))
average = sum(values)/len(values)
return average
print(get_average(studenci, ('zadania', 'quizy', 'testy')))
# >>> 3
答案 1 :(得分:0)
'Returns a list of the "averages" of each dictionary'
def dict_average(*args):
averages = []
for arg in args:
values = arg.values()
s = 0
i = 0
for v in values:
try:
s += v
i += 1
except TypeError:
s += 0
averages.append(s / i)
return averages