You need to enable JavaScript to run this app. Python实现read_schedules:将for循环生成的课程字典存入嵌套字典
优惠活动
大模型
产品
解决方案
定价
更多

Python实现read_schedules:将for循环生成的课程字典存入嵌套字典

核心实现步骤
  • 修正现有代码的作用域错误
    你之前把datain字典定义在循环外层,填充内容后从未将其赋值到外层data字典的对应位置;且因为字典是可变引用类型,不每次循环新建独立字典的话,最终data里所有条目会全部指向循环最后一次的字典值。
  • 确定外层字典的键
    你在判断逻辑里反复校验的insdata[m][1]就是课程编码(比如示例中的COMP110、COMP125),直接将这个值作为外层data的键即可匹配导师要求的结构。
  • 修正拼写不匹配的问题
    原代码中写的Instructer为拼写错误,需统一为示例要求的Instructor字段名。
整合后的函数实现

将已经验证正常的文件读取逻辑(生成insdata、locdata、timedata的部分)保留,替换循环和字典写入逻辑即可:

def read_schedules():
    # 下方为你已完成验证的文件读取逻辑,无需修改
    # insdata, locdata, timedata = 读取三个文件的逻辑
    
    data = {}
    # 提前展开通用匹配列表,避免循环内重复生成
    all_loc_codes = [b for a in locdata for b in a]
    all_time_codes = [b for a in timedata for b in a]

    for course_item in insdata:
        course_code = course_item[1]
        # 保留你原有的匹配判断逻辑
        if course_code in all_loc_codes and course_code in all_time_codes:
            # 每次循环新建独立的datain字典,避免引用污染
            datain = {
                "Name": course_item[0],
                "Instructor": course_item[2],
                "Location": [x[1] for x in locdata for y in x if y == course_code][0],
                "Days": [x[1] for x in timedata for y in x if y == course_code][0],
                "Start Time": [x[2] for x in timedata for y in x if y == course_code][0],
                "End Time": [x[3] for x in timedata for y in x if y == course_code][0]
            }
            # 将当前字典写入外层data的对应课程编码键下
            data[course_code] = datain
    
    return data
可选优化方向
  • 提前将locdata、timedata转换为“课程编码-对应信息”的查找字典,替代每次循环遍历全量列表的列表推导写法,减少重复计算
  • 删除原判断逻辑里重复校验course_code in timedata的冗余代码
  • 不再使用range(len(insdata))的索引写法,直接遍历列表元素可读性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 18:06:01