首页 > 解决方案 > 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)

标签: pythonarrayspython-3.xdictionary

解决方案


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

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)

推荐阅读