我有一些不同类型的学生名字和每种类型的分数.

students_exam_names = [exam_name1, exam_name2, exam_name3]
students_exam_score = [exam_score1, exam_score2, exam_score3]
students_quiz_names = [quiz_name1, quiz_name2]
students_quiz_score = [quiz_score1, quiz_score2]
students_homework_names = [homework_name1, homework_name2, homework_name3, homework_name4]
students_homework_score = [homework_score1, homework_score2, homework_score3, homework_score4]

这三种情况类似,如下所示.

我希望以嵌套dict的形式提供以下详细信息:

details = {'students_exam':{
    'exam_name1':exam_score1,
    'exam_name2':exam_score2,
    'exam_name3':exam_score3
},
'students_quiz':{
    'quiz_name1': quiz_score1,
    'quiz_name2': quiz_score2
},
'students_homework':{
    'homework_name1': homework_score1,
    'homework_name2': homework_score2,
    'homework_name3': homework_score3,
    'homework_name4': homework_score4,
}

每种学生类型的长度不同.我试着以下面的字典列表的形式获取它,但无法进一步.

students_exam = {}

for i in range(len(students_exam_names)):
  students_exam[students_exam_names[i]] = students_exam_score[i]

推荐答案

定义输入时,不要忘记使用':

students_exam_names = ['exam_name1', 'exam_name2', 'exam_name3']
students_exam_score = ['exam_score1', 'exam_score2', 'exam_score3']
students_quiz_names = ['quiz_name1', 'quiz_name2']
students_quiz_score = ['quiz_score1', 'quiz_score2']
students_homework_names = ['homework_name1', 'homework_name2', 'homework_name3', 'homework_name4']
students_homework_score = ['homework_score1', 'homework_score2', 'homework_score3', 'homework_score4']

然后,只需使用zip函数:

details = {'students_exam': dict(zip(students_exam_names, students_exam_score)),
           'students_quiz': dict(zip(students_quiz_names, students_quiz_score)),
           'students_homework': dict(zip(students_homework_names, students_homework_score))}

输出为:

{'students_exam': {'exam_name1': 'exam_score1', 'exam_name2': 'exam_score2', 'exam_name3': 'exam_score3'}, 'students_quiz': {'quiz_name1': 'quiz_score1', 'quiz_name2': 'quiz_score2'}, 'students_homework': {'homework_name1': 'homework_score1', 'homework_name2': 'homework_score2', 'homework_name3': 'homework_score3', 'homework_name4': 'homework_score4'}}

Python相关问答推荐

通过优化空间在Python中的饼图中添加标签

更改matplotlib彩色条的字体并勾选标签?

有症状地 destruct 了Python中的regex?

pyscript中的压痕问题

如何从数据库上传数据到html?

Odoo 16使用NTFS使字段只读

手动设置seborn/matplotlib散点图连续变量图例中显示的值

在代码执行后关闭ChromeDriver窗口

OpenCV轮廓.很难找到给定图像的所需轮廓

在我融化极点数据帧之后,我如何在不添加索引的情况下将其旋转回其原始形式?

使用np.fft.fft2和cv2.dft重现相位谱.为什么结果并不相似呢?

极点替换值大于组内另一个极点数据帧的最大值

Python:从目录内的文件导入目录

用来自另一个数据框的列特定标量划分Polars数据框中的每一列,

PYTHON中的pd.wide_to_long比较慢

根据过滤后的牛郎星图表中的数据计算新系列

如何关联来自两个Pandas DataFrame列的列表项?

为什么按下按钮后屏幕的 colored颜色 保持不变?

使用pythonminidom过滤XML文件

为什么在生成时间序列时,元组索引会超出范围?