[英]Calculate values from same dictionary using List comprehension
我必须使用字典来创建一个关于 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]}
我应该有一些这样的作为我的 output:
scores = {'student': ['s1', 's2', 's3'], 's1': [9, 9, 9], 's2': [8, 8, 8], 's3': [7, 7, 7],'avg': [9, 8, 7]}
我是 Pyhton(编程)的新手,我很难理解如何迭代每个项目。
感谢帮助!
以下是您的解决方案:
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]
你知道 Python dict
是如何工作的吗?
>>> d = {'key': 'value'}
>>> d
{'key': 'value'}
>>> d['otherKey'] = 'otherValue'
>>> d
{'key': 'value', 'otherKey': 'otherValue'}
所以猜猜你需要做什么来添加那个部分......
scores['avg'] = ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.