簡體   English   中英

如何在字典的元組中獲取值?

[英]How to get a value in a tuple in a dictionary?

我想使用lambda函數訪問字典中的元組中的值

我需要通過比較該班學生的平均成績來獲得每個學科的平均GPA

我嘗試使用lambda,但無法弄清楚。


grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0}

subjects = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}}


def highestAverageOfSubjects(subjects):
    return

輸出必須為['math','English']因為數學的平均GPA為3.0大於英語2.0的平均GPA

您可以通過使用帶有key功能的sort來輕松地對所有內容進行sorted

Grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0}
subject = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}}
result = sorted(subject, key=lambda x: sum(Grade[g] for _, g in subject[x]) / len(subject[x]), reverse=True)
print(result)

輸出:

['math','English']

如果作為中學,您想按學生人數排序:

result = sorted(subject, key=lambda x: (sum(Grade[g] for _, g in subject[x]) / len(subject[x]), len(subject[x])), reverse=True)
print(result)

實現方式的問題之一是,您在subject字典set用作值。 這意味着您必須覆蓋每個元素。 但是一旦有了元素,就可以像elem[1]那樣簡單地索引該值。

例如:

Grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0}
subject = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}}
for elem in subject['math']:
    print(elem[1])

輸出:

C
A

如果在上面的printprint(elem)那么您將看到類似以下內容:

('Larry', 'C')
('Jack', 'A')

這樣一來,您可以輕松擴展highAveSub(subject)實現以獲取所需的內容。

查找主題的平均成績:

def highAveSub(subname):
    total = 0
    for elem in subject[subname]:   #Because your values are of type set, not dict.
        total = total + grade[elem[1]]    #This is how you will cross-reference the numerical value of the grade. You could also simply use enums and I'll leave that to you to find out
    avg = total / len(subject[subname])
    return avg

暫無
暫無

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

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