如何使用zip将学生姓名、科目及分数列表转换为嵌套字典?
用Zip实现学生成绩嵌套字典
问题描述
给定学生姓名列表、科目列表及对应科目的分数列表,需转换为以学生名为键、科目-分数键值对为值的嵌套字典。
输入数据
studentName = ["kelly","Micheal","Agatha","Chris","frank","matthew"] subject = ["math","phy","chem"] math = [34,45,78,79,60,36] phy = [57,98,67,90,56,60] chem = [67,86,35,98,50,67]
解决方案代码
studentName = ["kelly","Micheal","Agatha","Chris","frank","matthew"] subject = ["math","phy","chem"] math = [34,45,78,79,60,36] phy = [57,98,67,90,56,60] chem = [67,86,35,98,50,67] # 按学生维度打包三科分数,每个元素对应一个学生的成绩元组 student_score_groups = zip(math, phy, chem) # 构建嵌套字典,同时调整指定姓名的大小写以匹配期望输出 student_grade_dict = {} for name, scores in zip(studentName, student_score_groups): # 对指定姓名做大小写转换 adjusted_name = name.lower() if name in ("Micheal", "Chris") else name # 将科目与分数配对成子字典 student_grade_dict[adjusted_name] = dict(zip(subject, scores)) # 格式化打印结果 import pprint pprint.pprint(student_grade_dict)
代码说明
- 分数打包:
zip(math, phy, chem)将三个分数列表按索引对齐,生成每个学生的三科成绩元组(如(34, 57, 67)对应kelly的成绩)。 - 嵌套字典构建:
- 遍历学生姓名与对应成绩元组,对
Micheal、Chris两个姓名做小写转换以匹配期望格式; - 用
dict(zip(subject, scores))将科目列表与成绩元组配对,生成每个学生的科目-分数子字典; - 把调整后的姓名作为键、子字典作为值,存入最终的嵌套字典。
- 遍历学生姓名与对应成绩元组,对
- 格式化输出:借助
pprint模块让输出结构更清晰,与期望格式一致。
输出结果
{ 'Agatha': {'chem': 35, 'math': 78, 'phy': 67}, 'chris': {'chem': 98, 'math': 79, 'phy': 90}, 'frank': {'chem': 50, 'math': 60, 'phy': 56}, 'kelly': {'chem': 67, 'math': 34, 'phy': 57}, 'micheal': {'chem': 86, 'math': 45, 'phy': 98}, 'matthew': {'chem': 67, 'math': 36, 'phy': 60} }
内容的提问来源于stack exchange,提问作者Stanley Omeje
相关产品推荐
相关产品推荐

