数据保存在一个以字典为元素的列表中,其中每个词典都包含单个学生的数据:学生的ID号,科目名称以及他/她在每个课程上获得的分数这两个部分考试分别。每个字典的格式如下:
{'ID' : _IDnumber_, 'subject' : _'Artificial Intelligence'_, 'Partial Exam 1' : _points1_, 'Partial Exam 2' : _points2_}
现在,我需要定义一个函数sum_partials()
,该函数接收一个自变量–包含学生数据的字典列表(如上所述),并返回相同的列表,但是以这样的方式进行了修改:每个字典将仅包含部分考试的总分(即总分),而不包含两次部分考试的分值。
例如结果:
[{'ID': 12217, 'subject': 'Artificial Intelligence', 'Total score': 55}, {'ID': 13022, 'subject': 'Artificial Intelligence', 'Total score': 85}, {'ID': 13032, 'subject': 'Artificial Intelligence', 'Total score': 47}]
我通过使用一个用于编辑每个学生的函数来做到这一点,该函数称为列表理解中的表达式:
def sum_partials(results):
# your code here
def update_student(student):
partial_exam1 = student['Partial Exam 1']
partial_exam2 = student['Partial Exam 2']
student.pop('Partial Exam 1')
student.pop('Partial Exam 2')
student['Total score'] = partial_exam1 + partial_exam2
return student
return [update_student(student) for student in results]
它可以完美工作,但是我是Python的新手,我想知道我是否可以重构代码!?是否存在仅使用列表推导或嵌套列表推导在一行中执行此操作的解决方案?
我的意思是,要完成所有我需要做的工作,而无需使用update_student()
函数,而只能使用list comprehensions
吗?
答案 0 :(得分:0)
请记住,在列表理解有效的同时,您可能希望优先考虑可读代码,而不是“仅因为这种类型的结构”。
在这里,一个简单的for
循环遍历您的学生列表就很好了。
def sum_partials(list_of_students):
for student in list_of_students:
student['Total score'] = student.pop('Partial Exam 1') + student.pop('Partial Exam 2')
return list_of_students
感谢@BoarGules使用pop
进行紧凑的单线计算。
答案 1 :(得分:0)
您可以使用以下listcomp:
lst = [{'ID': 12217, 'subject': 'Artificial Intelligence', 'Partial Exam 1' : 10, 'Partial Exam 2' : 20}]
[{'ID': i['ID'], 'subject': i['subject'], 'Total score': i['Partial Exam 1'] + i['Partial Exam 2']} for i in lst]
# [{'ID': 12217, 'subject': 'Artificial Intelligence', 'Total score': 30}]