python - How to compared two lists in python and return them in dictionary
问题描述
I have two lists:
names: ['Mary', 'Jack', 'Rose', 'Mary', 'Carl', 'Fred', 'Meg', 'Phil', 'Carl', 'Jack', 'Fred', 'Mary', 'Phil', 'Jack', 'Mary', 'Fred', 'Meg']
grades: [80, 88, 53, 80, 64, 61, 75, 80, 91, 82, 68, 76, 95, 58, 89, 51, 81, 78]
I want to be able to take the average of each persons test scores. For example, Mary pops up in the names list 4 times and I want to be able to take the test scores that are mapped to her and take that average.
The issue is how to compare the duplicate names with the test scores.
Note: I do know that the grades list is longer than the names list, but this was the two lists that was given to me.
Here is what I have done so far
def average_grades(names, grades):
averages = dict()
name_counter = 0
for name in names:
# if the name is the same
if name == names:
# count the occurence of the name
name_counter += 1
print(name_counter)
# cycle through the grades
# for grade in grades:
# print(grade)
解决方案
您可以并行迭代,找到它们的平均值并添加到字典中:
from itertools import groupby
from collections import defaultdict
names = ['Mary', 'Jack', 'Rose', 'Mary', 'Carl', 'Fred', 'Meg', 'Phil', 'Carl', 'Jack', 'Fred', 'Mary', 'Phil', 'Jack', 'Mary', 'Fred', 'Meg']
grades = [80, 88, 53, 80, 64, 61, 75, 80, 91, 82, 68, 76, 95, 58, 89, 51, 81, 78]
d = defaultdict(int)
f = lambda x: x[0]
for k, g in groupby(sorted(zip(names, grades), key=f), key=f):
grp = list(g)
d[k] = sum(x[1] for x in grp) / len(grp)
print(d)
推荐阅读
- android - 外键约束冲突在 Sqlite (android studio) 中不起作用
- django - 在 django 中使用 Allauth 社交注册的用户模型?
- reactjs - Redux-persist 迁移不迁移
- javascript - jQuery触发一个事件来改变文本值
- c# - 找不到方法:'System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert
- java - 验证 (PDF/PKI) 签名的必要步骤
- autodesk-forge - 模型实例化和转换
- r - 使用 docker 多阶段构建进行 R 开发和部署设置
- arduino - 如何控制带有串行输入和电位器的伺服
- docker - Apache Superset:无法第二次运行