繁体   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