我有一个嵌套的电影评分字典:
{‘John’:{‘星球大战’:1.0,'Silence':2.0,'Forrest‘:3.0},'Maria':{'Star Wars':nan,'Silence':1.0,'Forrest':2.0},'Mike':{'Star Wars':9.0,'Silence':nan,'Forrest':nan},
现在我想做一个函数,计算每部电影有多少人看过这部电影(score != nan),然后按降序排列。
我希望这一点是清楚的。提前感谢
发布于 2021-06-06 03:47:17
这将是我对这个排名系统的方法:
from collections import defaultdict
nan = 0 # to simplify the parsing...
dc = {'John' :{'Star Wars': 1.0, 'Silence': 2.0, 'Forrest' : 3.0},
'Maria':{'Star Wars': 0, 'Silence': 1.0, 'Forrest':2.0},
'Mike':{'Star Wars': 9.0, 'Silence': 0, 'Forrest': 0}}
scores = defaultdict(int)
for name, movies in dc.items():
for movie, score in movies.items():
if score: # not 0
scores[movie] += score
print(scores)
ranking = {k: v for k, v in sorted(scores.items(),
key=lambda item: -item[1])}
print(ranking) # {'Star Wars': 10.0, 'Forrest': 5.0, 'Silence': 3.0}https://stackoverflow.com/questions/67843962
复制相似问题