查找具有多个值的键的平均值

时间:2016-04-18 19:09:11

标签: python dictionary

我有一本字典,例如:

Jhon: 3, 4, 5
Mark: 5, 5, 5
Matthew: 7, 8 , 9

这是我的代码:

from statistics import mean
class1 = {}
for line in f:
            columns = line.split(":")
            if len(columns) == 2:
                names = columns[0]
                scores = columns[1].strip()
            else:
                pass
            if class1.get(names):
                class1[names].append(scores)
            else:
                class1[names] = list(scores)

我已经尝试过了:

for k, v in class1.items()
   print("{} : {scores}".format(names , mean(scores)

我收到错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

我也尝试过:

for k, v in class1.items():
   average = float(sum(v))/len(v)
for k, v in class1.items():
   print("{} : {}".format(names=k, average=v)

错误是:

Traceback (most recent call last):
  File "C:/Users/Onyeka/PycharmProjects/untitled/task3.py", line 59, in <module>
    print("{} : {scores}".format(names , mean(scores)))
  File "C:\Python34\lib\statistics.py", line 331, in mean
    T, total, count = _sum(data)
  File "C:\Python34\lib\statistics.py", line 161, in _sum
    for n,d in map(_exact_ratio, values):
  File "C:\Python34\lib\statistics.py", line 247, in _exact_ratio
    raise TypeError(msg.format(type(x).__name__))
TypeError: can't convert type 'str' to numerator/denominator

我希望输出像这样

   Jhon: 4
   Mark: 3
   Matthew: 8

是否也可以按照从最高到最低的顺序打印这些平均值?

1 个答案:

答案 0 :(得分:0)

我对你发布的一些内容感到有点困惑,包括字典的奇怪格式,但我想我基本上理解你想要的东西。这就是我解决它的方法:

from statistics import mean

f = {'Jhon': [3, 4, 5], 'Mark': [5, 5, 5], 'Matthew': [7, 8 , 9]}
averages = {}
for key in f:
    averages[key] = int(mean(f[key]))

print(averages)

输出是:

{'Matthew': 8, 'Mark': 5, 'Jhon': 4}