如何在python中比较两个列表并在字典中返回它们

时间:2019-11-09 09:16:25

标签: python arrays python-3.x dictionary

我有两个列表: 名称:['Mary', 'Jack', 'Rose', 'Mary', 'Carl', 'Fred', 'Meg', 'Phil', 'Carl', 'Jack', 'Fred', 'Mary', 'Phil', 'Jack', 'Mary', 'Fred', 'Meg']

等级:[80, 88, 53, 80, 64, 61, 75, 80, 91, 82, 68, 76, 95, 58, 89, 51, 81, 78]

我希望能够取得每个人的平均考试成绩。例如,玛丽在名称列表中弹出4次,我希望能够获取映射到她的测试成绩并取其平均值。

问题在于如何将重复的姓名与考试成绩进行比较。

注意:我确实知道成绩列表比名称列表长,但这是给我的两个列表。

这是我到目前为止所做的

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)

2 个答案:

答案 0 :(得分:0)

您可以并行进行迭代,找到它们的平均值并添加到字典中:

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)

答案 1 :(得分:0)

这是一种方法:

any

输出:

from collections import defaultdict, Counter

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]

score = defaultdict(int)
# this line initializes a default dict with default value = 0

frequency = Counter(names)
# this yields: Counter({'Mary': 4, 'Jack': 3, 'Fred': 3, 'Carl': 2, 'Meg': 2,'Phil': 2, 'Rose': 1})

for name, grade in zip(names, grades):
    score[name] = score.get(name,0)+(grade / frequency[name])
    # here you add the (grade of name / count of name) to each name,
    # score.get(name,0) this line adds a default value 0 if the key does not exist already

print(score)

注意:它忽略了最后一个年级,因为我不知道该怎么做。