簡體   English   中英

遍歷 Python 中的內部字典

[英]Iterate through Inner Dictionaries in Python

我是 Python 的初學者。 我正在練習一個用例以獲得存儲在字典中的學生的最終分數。 請你指導我有沒有辦法簡化這個?

 ScoreCard = {'Antony':{'maths':99,'english':33, 'science':100},'Jeff':{'maths':45,'english':99, 'science':73},
        'Mark':{'maths':77,'english':80, 'science':86}}

def sumofMarks(MarkList):
    SumMark = 0
    for k, v in MarkList.items():
        SumMark = SumMark + v
    return SumMark
        
def getMarks(Score, student):
    for k,v in Score.items():
        if student in Score.keys():
            newdic = Score[student]
            finalScore = sumofMarks(newdic)
            print("Final Score of:", student)
            return finalScore
        else:
            print("Student Not found in registry !")
            break            

getMarks(ScoreCard,'Jeff')

您可以使用values()獲取字典的所有值,並使用sum()獲取它們的總和:

ScoreCard = {'Antony': {'maths': 99, 'english': 33, 'science': 100},
             'Jeff': {'maths': 45, 'english': 99, 'science': 73},
             'Mark': {'maths': 77, 'english': 80, 'science': 86}}

def getMarks(Score, student):
    if student in Score:
        print(sum(Score[student].values()))
    else:
        print('Student not found')

getMarks(ScoreCard, 'Jeff')
# 217
ScoreCard = {'Antony':{'maths':99,'english':33, 'science':100},'Jeff':{'maths':45,'english':99, 'science':73},
        'Mark':{'maths':77,'english':80, 'science':86}}
name = "Jeff"
if name in ScoreCard.keys():
    for k,v in ScoreCard.items():
        if k==name:
            s = 0
            for k1,v1 in v.items():
                s+=v1
    print("Final Score of :",s)
else:
    print(name,"not found in registry")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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