簡體   English   中英

使用列表理解計算來自同一字典的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM