python-3.x - 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.
解决方案
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)
推荐阅读
- reactjs - 如何使用 nginx 在生产环境中使用 docker 服务我的 mern 应用程序?
- python - 用管道而不是逗号分隔列项
- reactjs - 为什么在没有任何变化的情况下使用 useEffect 重新渲染?
- javascript - 我如何将对象数组作为一个字符串解析为javascript中的对象
- ios - 覆盖 pushViewController 以每次显示默认 UIViewController
- python - 在哪里可以找到使用 boto3 编写自定义 AWS 凭证提供程序的文档?
- javascript - 增加选择器名称
- macos - 权限被拒绝@ apply2files - /usr/local/lib/node_modules/expo-cli/node_modules/extglob/lib/.DS_Store?
- powershell - Powershell:复制文件而不锁定
- flutter - Flutter 需要在图像上添加阴影