python - How to implement about calculating weighted average if it's without for loop -
this code following:
students = [{'name': 'tom', 'subjects': {'math': 50, 'english': 100, 'science': 72}}, {'name': 'alex', 'subjects': {'math': 100, 'english': 90, 'science': 95}}] weighting_coefficient = {'math': 2, 'english': 10, 'science': 8} total = sum(weighting_coefficient.values()) index, student in enumerate(students): subjects = student['subjects'] weighting_score = 0 subject, score in subjects.items(): weighting_score += weighting_coefficient[subject] * score students[index]['weighted_average'] = float(weighting_score)/total print students
the result:
[{'name': 'tom', 'subjects': {'english': 100, 'math': 50, 'science': 72}, 'weighted_average': 83.8}, {'name': 'alex', 'subjects': {'english': 90, 'math': 100, 'science': 95}, 'weighted_average': 93.0}]
i sure complete calculation, available implement codes if don't use foor-loop
it?
thanks @kevin guan great tip (helped me advance own "python career")
using list comprehension, suggested:
students = [{'name': 'tom', 'subjects': {'math': 50, 'english': 100, 'science': 72}}, {'name': 'alex', 'subjects': {'math': 100, 'english': 90, 'science': 95}}] weighting_coefficient = {'math': 2, 'english': 10, 'science': 8} total = sum(weighting_coefficient.values()) student in students: student['weighted_average'] = float( sum( [student['subjects'][subj] * weighting_coefficient[subj] subj in student['subjects'].keys() ] ) ) / total print students
the code looks messy @ first, create more variables hold key information (and make weighting_coefficients
shorter).
i've tested both original data set , 1 (not included here results matched using both op's method , method).
Comments
Post a Comment