我的代码如下:
students = [{'name': 'Tom',
'subjects': {'math': 50,
'english': 100,
'science': 72}},
{'name': 'Alex',
'subjects': {'math': 100,
'english': 90,
'science': 95}}]
weighting_coefficient = {'math': 2,
'english': 10,
'science': 8}
total = sum(weighting_coefficient.values())
for index, student in enumerate(students):
subjects = student['subjects']
weighting_score = 0
for subject, score in subjects.items():
weighting_score += weighting_coefficient[subject] * score
students[index]['weighted_average'] = float(weighting_score)/total
print students
结果是:
[{'name': 'Tom',
'subjects': {'english': 100, 'math': 50, 'science': 72},
'weighted_average': 83.8},
{'name': 'Alex',
'subjects': {'english': 90, 'math': 100, 'science': 95},
'weighted_average': 93.0}]
我肯定会完成计算,但是如果我不使用foor-loop
来实现代码,它是否可用?你知道吗
感谢@Kevin Guan给我的好建议(帮助我推进了自己的“Python生涯”)
使用列表理解,建议如下:
代码一开始看起来很混乱,但是您可以创建更多的变量来保存键信息(并缩短
weighting_coefficients
)。你知道吗我已经用原始数据集和一个额外的数据集进行了测试(不包括在这里,但使用OP的方法和我的方法匹配的结果)。你知道吗
相关问题 更多 >
编程相关推荐