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

Python 基于已有student_data嵌套字典生成课程班级信息嵌套字典

实现方案

直接上可运行的实现代码:

def organize_course_data(student_data):
    # 临时中间字典,用于归集每个课程每个班级的学生ID
    temp_collect = {}
    for student in student_data:
        stu_id = student["id"]
        # 遍历该学生的所有选课记录
        for enroll_info in student["enlistment"]:
            course = enroll_info["course code"]
            sec = enroll_info["section"]
            # 初始化不存在的课程、班级层级
            if course not in temp_collect:
                temp_collect[course] = {}
            if sec not in temp_collect[course]:
                temp_collect[course][sec] = []
            # 追加学生ID到对应班级
            temp_collect[course][sec].append(stu_id)

    # 整理为要求的输出格式,同时完成排序
    result = {}
    for course_code, sec_map in temp_collect.items():
        # 班级按字母升序排序,每个班级的学生ID按升序排序
        sorted_sec_list = [
            {"section": sec, "class list": sorted(stu_ids)}
            for sec, stu_ids in sorted(sec_map.items())
        ]
        result[course_code] = sorted_sec_list
    return result


# 测试调用示例
if __name__ == "__main__":
    # 你的student_data数据源放在这里
    student_data = [
        {'enlistment': [{'course code': 'UK 60', 'section': 'A'},
                        {'course code': 'GF 24', 'section': 'B'},
                        {'course code': 'ME 40', 'section': 'B'},
                        {'course code': 'VY 44', 'section': 'D'},
                        {'course code': 'EN 94', 'section': 'B'}],
         'id': '201001', 'paid': True, 'school': 'SOSE', 'year level': 2},
        {'enlistment': [{'course code': 'EQ 61', 'section': 'D'},
                        {'course code': 'UZ 22', 'section': 'B'},
                        {'course code': 'KS 36', 'section': 'B'},
                        {'course code': 'VH 63', 'section': 'A'},
                        {'course code': 'IW 81', 'section': 'C'}],
         'id': '211002', 'paid': True, 'school': 'JGSOM', 'year level': 1},
        {'enlistment': [{'course code': 'WE 15', 'section': 'D'},
                        {'course code': 'ZP 68', 'section': 'A'},
                        {'course code': 'GI 78', 'section': 'A'},
                        {'course code': 'GK 72', 'section': 'C'},
                        {'course code': 'FA 24', 'section': 'D'},
                        {'course code': 'UJ 28', 'section': 'A'}],
         'id': '201003', 'paid': True, 'school': 'JGSOM', 'year level': 2}
    ]
    output = organize_course_data(student_data)
    # 格式化打印输出,方便核对
    import json
    print(json.dumps(output, indent=4, ensure_ascii=False))

逻辑说明

  • 先用中间临时字典做数据归集,拆分复杂的嵌套操作,降低出错概率
  • 遍历所有学生的选课信息,把学生ID对应到对应课程的对应班级下
  • 归集完成后统一做排序:课程下的班级按字母升序排列,每个班级下的学生ID按升序排列
  • 最终组装成你需要的输出结构即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 12:18:02