python - Sorting a dictionary by average of list in value -
i have dictionary keys names , values lists of 3 integers (these scores of named people):
classscores={ 'bob':[1, 6, 3], 'jim':[6, 10, 3], 'fred':[0, 2] }
i need print sorted average of scores (highest first). have created working code this:
classaverages={} student in classscores: classaverages[student]=sum(classscores[student])/len(classscores[student]) student in sorted(classaverages, key=classaverages.get, reverse=true): print(student, "average:", sum(classscores[student])/len(classscores[student]))
however, feel inefficient uses 2 for
loops has go through every student twice. therefore looking suggestions incorporate sorting 2nd loop (presumably sorted function).
update: i've gone lambda, have defined before for
loop can use print averages:
classaverages=lambda student: sum(classscores[student]) / len(classscores[student]) student in sorted(classscores, key=classaverages, reverse=true): print(student, "average:", classaverages(student))
you can calculate average per student in key
function:
for student in sorted(classscores, key=lambda k: sum(classscores[k]) / len(classscores[k]), reverse=true):
using 2 loops marginally less efficient however; increased fixed cost per student determine order. missed opportunity re-use average in second loop when displaying averages:
classaverages={} student in classscores: classaverages[student] = sum(classscores[student]) / len(classscores[student]) student in sorted(classaverages, key=classaverages.get, reverse=true): print(student, "average:", classaverages[student])
you loop on dictionary items in generator expression calculate averages, sort on averages, , display calculated average in 1 operation:
student_averages = ((sum(scores) / len(scores), s) s, scores in classscores.items()) average, student in sorted(student_averages, reverse=true): print(student, "average:", average)
the generator produces data in (average, student)
pairs ease sorting (we don't need key
pick out second value).
Comments
Post a Comment