You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表传递异常:average()报NoneType不可迭代错误

Python列表append()返回None导致迭代报错的解决方法

问题现象

成绩计算器中,calculate_grade_final()调用average()能正常计算课程平均分(如92.73),但输入目标成绩95后,lowest_grade()函数内的average()调用触发如下错误:

Traceback (most recent call last):
File ".../GradeCalculatorPlus/run.py", line 127, in <module>
calculate_grade_final(summatives, formatives, course)
File ".../GradeCalculatorPlus/run.py", line 60, in calculate_grade_final
lowest_grade_possible = lowest_grade(desired_end_grade, summatives, formatives)
File ".../GradeCalculatorPlus/run.py", line 38, in lowest_grade
if average(summatives_copy.append(next_summative_grade), formatives_copy) >= desiredGrade:
File ".../GradeCalculatorPlus/run.py", line 26, in average
int_summatives = [int(numeric_string) for numeric_string in summatives]
TypeError: 'NoneType' object is not iterable

错误根源

list.append()方法是原地修改列表,它的返回值是None。直接将summatives_copy.append(next_summative_grade)作为参数传给average(),相当于让average()去迭代None,自然触发「无法迭代NoneType对象」的错误。

解决方案

将列表追加操作与average()调用分开执行:

  1. 先调用append()修改列表
  2. 再将修改后的列表传入average()

修改前错误代码

# lowest_grade()中的错误调用
if average(summatives_copy.append(next_summative_grade), formatives_copy) >= desiredGrade:

修改后正确代码

# 先执行追加操作,原地修改summatives_copy
summatives_copy.append(next_summative_grade)
# 再将修改后的列表传入average()
if average(summatives_copy, formatives_copy) >= desiredGrade:

额外注意

如果需要避免修改原summatives列表,确保summatives_copy是原列表的独立副本,比如:

# 创建原列表的浅拷贝
summatives_copy = summatives.copy()
# 或者用list()构造器
summatives_copy = list(summatives)

终端输入记录

Please enter your FORMATIVE grades:
Enter a number grade (no fractions or percentages!) (Type 'stop' to stop the loop)98
...
Average for AP American Lit Lang/Comp:92.73124999999999
What is your desired end grade for AP American Lit Lang/Comp? 95

内容的提问来源于stack exchange,提问作者SaltyScrimp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:40:55