Python词典问题

2024-10-02 18:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在努力将两个值附加到字典中,请参阅下面的代码,但我想将平均分数附加到它们的名称中。你知道吗

 Question = raw_input("""How would you like to view the class?
 A) By Average, highest to lowest:
B) By Highest score, highest to lowest:
C) By Alphaetical order:
""")
Question = Question.title()
if Question == "A" :
    for key, value in Classdict.items():
        Avg = sum(map(int, value))/ float(len(value))
        global AvgDict
        AvgDict = {}
        for key in Classdict:
            if key in AvgDict:
                AvgDict[key].append(Avg)
            else:
                AvgDict[key] = Avg
        print AvgDict
    Classopen.close()
    Questiontwo = raw_input("""How would yuu like to view it?
A)By highest score, highest to lowest:
B)By Alphaetical order: 
""")

    Questiontwo = Questiontwo.title()
    if Questiontwo == "A":
        print "You selected highest score, highest to lowest"
        sortedavghigh = sorted(AvgDict.items(), key=operator.itemgetter(1))
        print sortedavghigh[::-1]
    elif Questiontwo == "B":
        print "You selected to sort it alphabetically"
        sortedavgapha = sorted(AvgDict.items(), key=operator.itemgetter(0))
        print sortedavgalpha

Tags: tokeyinbyifvalueitemsavg
2条回答

将值赋给AvgDict时,请确保将其作为列表,否则,在使用.append(Avg)时,它将不起作用。 你可以这样植入它:

AvgDict[key] = [Avg]

从表面上看,这句话是错误的:

AvgDict[key] = Avg

我认为应该是:

AvgDict[key] = [Avg]

这样你就有了一个可以附加的列表。你知道吗

附加的代码也可以这样写,我觉得这看起来更清楚一些:

if key not in AvgDict:
    AvgDict[key] = []
AvgDict[key].append(Avg)

相关问题 更多 >