【发布时间】:2021-03-09 18:37:52
【问题描述】:
鉴于以下数据,我如何创建一个字典,其中键是学生的姓名,值是字典,键是测试,值是他们在其中得到的成绩。
grades = [
['Students', 'Test 1', 'Test 2', 'Test 3'],
['Tomas', '100', '90', '80'],
['Marcos', '88', '99', '111'],
['Flavia', '45', '56', '67'],
['Ramon', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Federico', '89', '97', '101']
]
我试过这样做,但我不知道为什么它没有正确显示成绩。
notas_dict={}
def dic(etiquets, notas):
for i in range(len(etiquets)):
notas_dict[etiquets[i]]=int(notas[i])
return notas_dict
dic(['Test 1','Test 2', 'Test 3'], ['100','80','90'] )
dic_final={}
for line in grades[1:]:
line_grades=[int(element) for element in line[1:]]
dic_final[line[0]]=dic(['Test 1','Test 2', 'Test 3'], line_grades)
print(dic_final)
输出应该是:
{'Tomas': {'Test 1': 100, 'Test 2': 90, 'Test 3': 80}, 'Marcos': {'Test 1': 88, 'Test 2': 99, 'Test 3': 111}, 'Flavia': {'Test 1': 45, 'Test 2': 56, 'Test 3': 67}, 'Ramon': {'Test 1': 59, 'Test 2': 61, 'Test 3': 67}, 'Ursula': {'Test 1': 73, 'Test 2': 79, 'Test 3': 83}, 'Federico': {'Test 1': 89, 'Test 2': 97, 'Test 3': 101}}
【问题讨论】:
-
dic是什么?你没有在任何地方定义它。另外,你得到什么输出? -
dic 是我创建的一个函数,用于创建将作为值的字典(我的错误是我忘了放代码,但我编辑了它)。我得到的输出是:
{'Tomas': {'Control 1': 89, 'Control 2': 97, 'Control 3': 101}, 'Marcos': {'Control 1': 89, 'Control 2': 97, 'Control 3': 101}, 'Flavia': {'Control 1': 89, 'Control 2': 97, 'Control 3': 101}, 'Ramon': {'Control 1': 89, 'Control 2': 97, 'Control 3': 101}, 'Ursula': {'Control 1': 89, 'Control 2': 97, 'Control 3': 101}, 'Federico': {'Control 1': 89, 'Control 2': 97, 'Control 3': 101}}
标签: python-3.x dictionary for-loop