我必须使用字典来创建学生在Python上的成绩数据库。它必须包含字段name、score1、score2和score3。然后我必须创建第五个名为average的字段,并将其填充为以前成绩的加权平均值((score1x20+score2x30+score3x50)/100)。我只能使用列表/字典推导。
我的输入是这样的:
scores = {'student': ['s1', 's2', 's3'], 's1': [9, 9, 9], 's2': [8, 8, 8], 's3': [7, 7, 7]}
,我应该有一些像这样的输出:
scores = {'student': ['s1', 's2', 's3'], 's1': [9, 9, 9], 's2': [8, 8, 8], 's3': [7, 7, 7],'avg': [9, 8, 7]}
我对python(编程)非常陌生,我很难理解如何迭代每个项目。
感谢你的帮助!
解决方案如下:
scores = {
'student': ['s1', 's2', 's3'],
's1': [9, 9, 9],
's2': [8, 8, 8],
's3': [7, 7, 7]
}
# So now we have to search for every
# key in 'student' and calculate our output
avg = [] # This is our output for "avg" key
for i in scores['student']: # In each iteration i is that key, which
# weighted average we want to calculate
current_score = scores[i]
avg.append((current_score[0] * 20 + current_score[1] * 30 + current_score[2] * 50) // 100)
# Right up there we're calculating your weighted average of the previous
# grades
# and appending it to avg list
scores['avg'] = avg
print(scores)
scores = {'student': ['s1', 's2', 's3'], 's1': [9, 9, 9], 's2': [8, 8, 8], 's3': [7, 7, 7],'avg': [9, 8, 7]}
那么你要做的就是加上这部分:
'avg': [9, 8, 7]
你知道Pythondict
是如何工作的吗?
>>> d = {'key': 'value'}
>>> d
{'key': 'value'}
>>> d['otherKey'] = 'otherValue'
>>> d
{'key': 'value', 'otherKey': 'otherValue'}
猜猜你要做什么来添加那部分…
scores['avg'] = ...