以下是我的代码:
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来实现代码,是否可用呢?
发布于 2015-10-10 04:50:57
谢谢你给我的好建议(帮我推进了我自己的"Python事业“)
使用列表理解,如建议的:
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 student in students:
student['weighted_average'] = float( sum( [student['subjects'][subj] * weighting_coefficient[subj] for subj in student['subjects'].keys() ] ) ) / total
print students起初,代码看起来很混乱,但是您可以创建更多的变量来保存关键信息(并使weighting_coefficients更短)。
我已经用原始数据集和额外的数据集进行了测试(这里不包括,但是使用OP的方法和我的方法匹配的结果)。
https://stackoverflow.com/questions/33050139
复制相似问题