我想计算列表中“分数”(字典值)的中位数。
my_dict = {"John": [{"class": "math", "score": 100, "year": 2014}, {"class": "english", "score": 85, "year": 2015}, {"class": "science", "score": 90, "year": 2015}],
"Timmy": [{"class": "math", "score": 87, "year": 2014}, {"class": "english", "score": 91, "year": 2015}],
"Sally":[{"class": "math", "score": 95, "year": 2014}]}
输出将如下所示:
new_dict = {"John": 90, "Timmy": 89, "Sally": 95}
我想我需要根据分数对 my_dict 进行排序,然后计算中值。如果不使用外部包装,就无法弄清楚任一步骤。
任何帮助将不胜感激!Python 新手。
您可以使用统计中的中位数。
from statistics import median
my_dict = {"John": [{"class": "math", "score": 100, "year": 2014}, {"class": "english", "score": 85, "year": 2015}, {"class": "science", "score": 90, "year": 2015}],
"Timmy": [{"class": "math", "score": 87, "year": 2014}, {"class": "english", "score": 91, "year": 2015}],
"Sally":[{"class": "math", "score": 95, "year": 2014}]}
new_dict = {}
for k, v in my_dict.items():
m = []
for l in v:
m.append(l["score"])
new_dict[k] = median(m)
print(new_dict)
如果您不想使用包并编写自己的函数,则可以调用:
def median(lst):
n = len(lst)
s = sorted(lst)
return (sum(s[n//2-1:n//2+1])/2.0, s[n//2])[n % 2] if n else None
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句