简体   繁体   中英

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)) :

>>> 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:

>>> 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 .

EDIT2:

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.

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:

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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