2016-04-24 62 views
0

我知道这是一个简单的错误,但一直在看它!我在哪里添加float或int以防止出现以下错误消息? int对象不是可用的。使用字典时int对象不可迭代

如何从最高分到最低分打印它。我可以添加reverse = True吗?我收到一个元组错误。 -

scores = {} #You'll need to use a dictionary to store your scores; 

with open("classscores1.txt") as f: 
    for line in f: 
     name, score = line.split() #store the name and score separately (with scores converted to an integer) 
     score = int(score) 
     if name not in scores or scores[name] < score: 
      scores[name] = score # replacing the score only if it is higher: 

    for name in sorted(scores): 
     print(name, "best score is", scores[name]) 
     print("{}'s best score is {}".format(name, max(scores[name]))) 
+4

'int'对象在任何地方都不可迭代*。 – jonrsharpe

+1

'max(scores [name])'在这里,'scores [name]'只是一个单独的分数,一个'int'。这应该是该名称的分数列表吗? –

+0

最后一行,大概是引发错误的那一行,看起来应该和以前的行完全一样。所以你可能应该删除那个有问题的行。 –

回答

1

的问题是这一行:

print("{}'s best score is {}".format(name, max(scores[name]))) 

在这里,您要采取的scores[name]max,这仅仅是一个整数。看代码,好像你已经十分小心,值是最大值,所以你可以把上面一行

print("{}'s best score is {}".format(name, scores[name])) 

如上print声明。 (此外,由于这两个print线将打印同样的事情,你也许可以删除这两个中的一个。)


从最高打印到最低得分,改变你的for循环,这样的事情:

for name in sorted(scores, key=scores.get, reverse=True): 
    ... 

此使用scores.get功能键scores排序的名字,即它按在字典中的值,并且reverse=True使得排序从最高到最低。

+0

我如何从最高分到最低分打印它。我可以添加reverse = True吗?我收到一个元组错误。 – Canadian1010101

+0

@ Canadian1010101看我的编辑。 –