使用列表理解计算来自同一字典的值

Calculate values from same dictionary using List comprehension

我必须使用字典来创建 Python 上学生成绩的数据库。它必须包含字段 name、score1、score2 和 score3。然后,我必须创建名为 average 的第五个字段,并用之前成绩的加权平均值 ((score1x20+score2x30+score3x50)/100) 填充它。我只能用List/dictionary理解

我的输入是这样的:

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]}

我是 Pyhton(编程)的新手,我很难理解如何迭代每个项目。

感谢帮助!

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'] = ...

下面是您的解决方案:

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)