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

Python文件读取与列表处理问题:修复出勤统计函数仅返回单个结果的错误

修复出勤统计函数,返回所有符合条件的学生姓名

你遇到的问题有两个核心原因:

  1. return语句位置错误:你的poor_attendance函数里,return w写在for循环内部,这会让函数在找到第一个符合条件的学生后立刻终止并返回,不会继续检查剩下的学生。
  2. 循环逻辑错误:你遍历的是attendance里的数值(比如10、6这些),然后用这个数值作为names列表的索引,这完全是错误的——索引应该是0、1、2这类位置序号,不是出勤次数本身,这甚至可能导致索引越界报错。

下面是修复后的代码,我会一步步说明改动点:

def file(filename):
    names = []
    attendance = []
    with open(filename) as data_file:
        for line in data_file:
            line_data = line.split(',')
            names.append(line_data[0].strip())
            attendance.append(int(line_data[1].strip()))
    return names, attendance

def poor_attendance(names, attendance):
    # 创建一个空列表,用来收集所有符合条件的学生姓名
    poor_students = []
    # 使用zip同时遍历姓名和对应的出勤次数,配对处理
    for name, count in zip(names, attendance):
        if count < 5:
            poor_students.append(name)
    # 循环结束后,返回整个列表
    return poor_students

def main():
    names, attendance = file("school.txt")
    poor_students = poor_attendance(names, attendance)
    # 处理列表的打印,让输出更友好
    print("The following students attendance is less than 50%:")
    for student in poor_students:
        print(f"- {student}")

if __name__ == '__main__':
    main()

关键改动说明:

  • 在poor_attendance里初始化了poor_students列表,用来存储所有符合条件的学生,而不是找到一个就返回
  • 用zip(names, attendance)把姓名和对应的出勤次数一一配对,这样遍历的时候能直接拿到每个学生的姓名和他的出勤次数,避免了索引错误
  • 把return移到循环外面,等所有元素遍历完成后,再返回收集好的列表
  • main函数里修改了打印逻辑,把列表里的每个学生单独打印,输出更清晰

运行这段代码后,就能正确输出Daniel和Jake两个学生了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:47:32