如何使用python从数据结构中提取字典?
这是一个名为grade_list的表格,它将学生的名字映射到他们考试成绩的列表中。等级应从字符串转换为整数。例如,grade_列出了['Thorny']=[100,90,80]。有人能帮我吗如何使用python从数据结构中提取字典?,python,python-3.x,Python,Python 3.x,这是一个名为grade_list的表格,它将学生的名字映射到他们考试成绩的列表中。等级应从字符串转换为整数。例如,grade_列出了['Thorny']=[100,90,80]。有人能帮我吗 grades = [ #here is the table ['Student', 'Exam 1', 'Exam 2', 'Exam 3'], ['Thorny', '100', '90', '80'], ['Mac', '88', '99', '111'], ['Far
grades = [ #here is the table
['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
['Thorny', '100', '90', '80'],
['Mac', '88', '99', '111'],
['Farva', '45', '56', '67'],
['Rabbit', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Foster', '89', '97', '101']
]
只需使用
dict
遍历列表即可:
grades_dict = dict((x[0],x[1:]) for x in grades[1:])
grades_dict
输出:
{'Farva': ['45', '56', '67'],
'Foster': ['89', '97', '101'],
'Mac': ['88', '99', '111'],
'Rabbit': ['59', '61', '67'],
'Thorny': ['100', '90', '80'],
'Ursula': ['73', '79', '83']}
和等级[棘手的]
:
['100', '90', '80']
使用将值映射到整数的字典理解:
{x[0]: list(map(int, x[1:])) for x in grades[1:]}
示例:
grades = [ #here is the table
['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
['Thorny', '100', '90', '80'],
['Mac', '88', '99', '111'],
['Farva', '45', '56', '67'],
['Rabbit', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Foster', '89', '97', '101']
]
print({x[0]: list(map(int, x[1:])) for x in grades[1:]})
# {'Thorny': [100, 90, 80],
# 'Mac': [88, 99, 111],
# 'Farva': [45, 56, 67],
# 'Rabbit': [59, 61, 67],
# 'Ursula': [73, 79, 83],
# 'Foster': [89, 97, 101]}
这将输出一个字典,名称作为键,标记列表将每个标记转换为整数作为键的值。只需运行这段代码
grades = [ #here is the table
['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
['Thorny', '100', '90', '80'],
['Mac', '88', '99', '111'],
['Farva', '45', '56', '67'],
['Rabbit', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Foster', '89', '97', '101']
]
dict = {}
for student_data in grades:
if student_data[0] == "Student":
continue
else:
temp_list = []
temp_list.append(int(student_data[1]))
temp_list.append(int(student_data[2]))
temp_list.append(int(student_data[3]))
dict[student_data[0]] = temp_list
print(dict)
针对上述问题的简单一行程序:
grades\u dict=dict(map(lambda x:(x[0],x[1:),grades))
您可以直接使用字典理解,而不是迭代列表,然后将其转换为字典。更像是蟒蛇
grades = [ #here is the table
['Student', 'Exam_1', 'Exam_2', 'Exam_3'],
['Thorny', '100', '90', '80'],
['Mac', '88', '99', '111'],
['Farva', '45', '56', '67'],
['Rabbit', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Foster', '89', '97', '101']
]
grade = {g[0]:g[1:] for g in grades[1:]}
print(grade)
# Output
#{'Thorny': ['100', '90', '80'], 'Mac': ['88', '99', '111'], 'Ursula': ['73', '79', '83'], 'Farva': ['45', '56', '67'], 'Foster': ['89', '97', '101'], 'Rabbit': ['59', '61', '67']}
你能分享一下你到目前为止所做的尝试吗?你添加了三次
student\u数据[1]
。这将产生错误的输出刚刚修复。谢谢