因此,如果我能够嵌套字典,我的代码看起来会最整洁。 我的问题是:
下面是我尝试使用的一些代码。请告诉我正确的格式是什么,可能有什么错误。。。谢谢!在
Student.Alice = {
Student.Alice.Math = {
'math1'= 100
'math2'= 98
'math3' = 89
'math4' = 91
'math5' = 77
'math6' = 90
'math7' = 82
'math8' = 100
'math9' = 79
'math10' = 100
}
Student.Alice.English = {
'english1' = 100
'english2' = 97
'english3' = 98
'english4' = 88
'english5' = 94
'english6' = 95
'english7' = 98
'english8' = 82
'english9' = 84
'english10' = 99
}
Student.Alice.Science = {
'science1' = 78
'science2' = 89
'science3' = 88
'science4' = 92
'science5' = 92
'science6' = 91
'science7' = 93
'science8' = 88
'science9' = 99
'science10' = 87
}
Student.Alice.French = {
'french1' = 100
'french2' = 100
'french3' = 99
'french4' = 104
'french5' = 103
'french6' = 97
'french7' = 94
'french8' = 93
'french9' = 75
'french10' = 93
}
}
可能是这样的:
这里,
students
是一个字典,它的键是学生的名字(这里只显示了Alice,但是您可以添加更多)。每个学生都是一本字典,其关键字是他或她注册的科目。科目是分数表。也就是说,我们不必使用带有french3
这样的关键字的字典,这些关键字是多余的,因为我们已经知道它们是法语的分数,而且我们已经知道它是第三项,所以我们只需将它们按顺序放在一个列表中,它们的顺序决定了访问它们的索引。(Python列表项编号以0开头,这与原始编号稍有不同,但如果要显示从1开始编号的条目,则应调整它们。)现在要计算爱丽丝的数学总分,你可以写下:
^{pr2}$或者看看爱丽丝所有的分数:
或者看看爱丽丝的第三个法语乐谱:
请注意:在外部字典中使用}会是一个更好的名字。在
students
以外的名称可能更好,因为这实际上是一个分数的集合。学生和科目级别就在那里,你可以指定你想要的分数!所以只要scores
或者{嵌套词典在未来将导致一个痛苦的世界。我强烈建议学习面向对象编程和
class
es。下面是一个不工作但方向正确的例子。在1,2)是的,可以使用嵌套字典。在
3)您可以通过以下方式访问子字典元素:
^{pr2}$它将输出
4
所以在你的例子中,你可以有一个叫做学生的字典,每个学生都有一个科目字典,每个科目都有一个成绩表。有点像
为了得到Bob的第二个数学成绩,你可以使用
students['Bob']['Maths'][1]
(不要忘了列表项从0开始索引)。在相关问题 更多 >
编程相关推荐