首页 > 解决方案 > Find the average of a value in a list of tuples within a list of dictionaries in Python

问题描述

I'm not sure why the following code isn't looping through the entire list and summing all of the targeted values. It's only looping through the first item within my list.

def average_grade(students):
    sum = 0
    grades_num = 0
    for s in students:
        for assignment_name, grade in s['assignments']:
            sum += grade
            grades_num += 1
        average = sum / grades_num
        return average
average_grade(students)   

I can print all of the grades for my entire list, but when I attempt to sum the grade it will stop at the first dictionary.

标签: python-3.x

解决方案


The return statement is in the loop so at the end of the first iteration the function returns. Just un-indent the average calculation and the return statement.

def average_grade(students):
    sum = 0
    grades_num = 0
    for s in students:
        for assignment_name, grade in s['assignments']:
            sum += grade
            grades_num += 1
    average = sum / grades_num
    return average

average_grade(students)  

推荐阅读