简体   繁体   中英

Finding the average of specific values in a dictionary

I have a dictionary that looks like this. . .

students_marks = {"barry": [20,25,30], "fred": [12,14,16], "sarah": [32,30,28]

and so forth, I'm able to add more keys with values to the dictionary. the values are marks for each assignment

I'm trying the get the average of all the students in the first assignment eg. barry - 20, fred - 12, sarah - 32

this is my code so far

students_marks = {"barry": [20,25,30], "fred": [12,14,16], "sarah": [32,30,28]}

def get_below_average_df_report_marks_report():
    sum(float(x[0] for x in students_marks.values())/len(students_marks))

I'm getting the error: TypeError: float() argument must be a string or a number, not 'generator'

The problem is that you are trying to cast to float before computing the sum, it should be float(sum... instead of sum(float... .

>>> float(sum(x[0] for x in students_marks.values()))/len(students_marks)
21.333333333333332

As far as readability goes, I prefer this solution:

>>> from operator import itemgetter
>>> first_score = itemgetter(0)
>>> num_students = float(len(students_marks))
>>> sum(map(first_score, students_marks.values()))/num_students
21.333333333333332

If you prefer a solution without an import statement, this one would be equivalent:

>>> first_score = lambda scores: scores[0]
>>> num_students = float(len(students_marks))
>>> sum(map(first_score, students_marks.values()))/num_students
21.333333333333332

Note that if you are using Python 3 the casts to float are unnecessary because the / operator already performs floating point division by default.

Your float cast is obsolete:

def get_below_average_df_report_marks_report():
    sum((x[0] for x in students_marks.values())/len(students_marks)

You were trying to convert the generator object x[0] for x in students_marks.values() into a float, which is not possible and caused your error.

Notice that in Python 3 you don't have to convert the values to a float first. Division always returns a float. In python 2, you can use from __future__ import division to enforce this behaviour.

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