簡體   English   中英

Python 將值附加到字典

[英]Python appending values to dictionary

我必須制作這個程序,我必須按字母轉換總和、平均函數和等級(下面循環中的 A、B)並附加到字典中,我嘗試在 if 函數中手動打印,但我必須實際附加並顯示湯姆': ['CS', [90, 75, 77], [242, 80.67], 'B']。

graDict = {'Tom': ['CS', [90, 75, 77]], 'Adam': ['CS', [70, 75, 87, 77]]}
def Average(graDict):
    total = 0
    values = graDict[sName][1]
    for i in values:
        total += i 
     #have to get this total that makes the grade sum and append to dictionary
    return total / len(values)
        #have to get the return in Average(graDict) and append to Dictionary

#iteration
for sName in list(graDict.keys()):
    value = Average(graDict) #getting average calc above
  
#I have to transform the average functions and grade by letters(A,B in the loop below) and append to dictionary, I tried print manually in the if function but I have to actually append and show Tom': ['CS', [90, 75, 77], [242, 80.67], 'B'].
  
 if value > 90:
        print(sName,graDict[sName][1] + "[avg",'{0:.2f}'.format(value),"] earns grade = A")
    elif value > 80:
        print (sName,graDict[sName][1], "[avg",'{0:.2f}'.format(value),"]earns grade = B")

我有點迷失所以如果你有任何線索讓我知道

您可以遍歷字典,使用sumlen函數來獲得答案。 這是完成它的一種快速而骯臟的方法。

graDict = {'Tom': ['CS', [90, 75, 77]], 'Adam': ['CS', [70, 75, 87, 77]], 'Joe':['CS',[]]}
#with example including someone with no test scores

letterGrade = {'A':(90,101),'B':(80,90),'C':(70,80),'D':(60,70),'F':(0,60)}
#letterGrade defines all the ranges of values for the letter grade

#now iterate through the dictionary
for name,testScore in graDict.items():

    #calculate the total using sum function
    total = sum(testScore[1])

    #calculate the average using total/len of scores. use round to 2 decimal places
    #if there were no scores, then avg is zero. check for len to avoid div by zero
    avg = round(total / len(testScore[1]),2) if len(testScore[1]) > 0 else 0

    #get the letter grade by iterating thru the dictionary
    grade = [g for g,r in letterGrade.items() if r[0] <= avg < r[1]][0]

    #create a new list and append it to the existing list
    testScore += [[total,avg,grade]]

    #replace old value with new value
    graDict[name] = testScore

print (graDict)

輸出將是:

{'Tom': ['CS', [90, 75, 77], [242, 80.67, 'B']], 'Adam': ['CS', [70, 75, 87, 77], [309, 77.25, 'C']], 'Joe': ['CS', [], [0, 0, 'F']]}

暫無
暫無

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

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