2016-04-24 29 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看我的編輯。 –