简体   繁体   English

在值列表中查找平均值

[英]Find Average in a list of values

EDIT: 编辑:

This is not a duplicate of finding average values of a list because this list is a value that is assigned to a key. 这不是查找列表平均值的重复项,因为此列表是分配给键的值。

Had to clear that up for those who didn't get it. 不得不为那些不了解它的人清除它。

I have a dictionary where every key has a list/multiple of values: 我有一本字典,其中每个键都有一个列表/多个值:

'Jimin ': ['0', '0', '0', '0', '0', '0'], 'Jin': ['1', '0'],

I want to print out the average of the values for every key eg: 我想打印出每个键的平均值,例如:

'Jimin ':[0], 'Jin': [0.5],

I have already tried: 我已经尝试过:

avgDict = {}
for k,v in StudentGrades.items():
    # v is the list of grades for student k
    avgDict[k] = sum(v)/ float(len(v))

But I get the error code: 但是我得到了错误代码:

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

And I have also tried: 我也尝试过:

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

But I get the error code: 但是我得到了错误代码:

Traceback (most recent call last):
File "C:/Users/Onyeka/Documents/Onyeka/Computer Science/Controlled            `   Assessment/Programming Project/task3.py", line 68, in <module>`
print("{} : {}".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
>>> x = {'Jimin ': ['0', '0', '0', '0', '0', '0'], 'Jin': ['1', '0']}
>>> {k: sum(int(i) for i in v) / float(len(v)) for k, v in x.items()}
{'Jimin ': 0.0, 'Jin': 0.5}

But if you need the average in a list: 但是,如果您需要列表中的平均值:

>>> x = {'Jimin ': ['0', '0', '0', '0', '0', '0'], 'Jin': ['1', '0']}
>>> {k: [sum(int(i) for i in v) / float(len(v))] for k, v in x.items()}
{'Jimin ': [0.0], 'Jin': [0.5]}

Or, you could directly convert to float and then you don't need float(len(v)) : 或者,您可以直接转换为float ,然后不需要float(len(v))

>>> x = {'Jimin ': ['0', '0', '0', '0', '0', '0'], 'Jin': ['1', '0']}
>>> {k: [sum(float(i) for i in v) / len(v)] for k, v in x.items()}
{'Jimin ': [0.0], 'Jin': [0.5]}

Another approach is to define your avg function and have it called during the build of your new dictionary with dictionary comprehension, this way: 另一种方法是定义您的avg函数,并在使用字典理解功能构建新字典的过程中调用它,方法是:

>>> d = {'Jimin': ['0', '0', '0', '0', '0', '0'], 'Jin': ['1', '0']}
>>> 
>>> def avg(lst):
        return sum(map(float,lst))/len(lst)

>>> {k:avg(v) for k,v in d.items()}
{'Jin': 0.5, 'Jimin': 0.0}

EDIT: 编辑:

What you got there as error message was due to the fact that your items in list values are string , so you need to type cast them to int before doing arithmetic operation, that's why you see on the this solution: map(float, lst) , which is converting every element of the list from string to float . 您收到的错误消息是由于列表值中的项目是string ,因此您需要在进行算术运算之前将其类型转换为int ,这就是为什么在此解决方案上看到的原因: map(float, lst) ,它将列表中的每个元素从stringfloat

EDIT2: 编辑2:

If all you want is to print averages, then the following will do: 如果您只想打印平均值,则可以执行以下操作:

>>> for k,v in d.items():
        print('{0} : {1}'.format(k,avg(v)))


Jin : 0.5
Jimin : 0.0

The reason your first approach does not work is, that you save the grades as a list of string. 您的第一种方法不起作用的原因是,您将成绩保存为字符串列表。 One way to make your code work would be to convert the strings to numbers before adding them to the dictionary using the int function. 使代码工作的一种方法是将字符串转换为数字,然后再使用int函数将其添加到字典中。

So this code 所以这段代码

        if class1.get(names):
            class1[names].append(scores)
        else:
            class1[names] = list(scores)

would become this: 会变成这样:

        if class1.get(names):
            class1[names].append(int(scores))
        else:
            class1[names] = list(int(scores))

You could use the mean() method of the statistics module: 您可以使用统计信息模块的mean()方法:

Code: 码:

from statistics import mean

A = {'Jimin': [1,2,3], 'Jin': [1,2,3]}

for key in A.keys():
    A[key] = mean(A.get(key))

This yields: 这样产生:

A = {'Jimin': 2.0, 'Jin': 2.0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM