2011-10-05 118 views
0

我想排序Python中的字典。因爲我是新的,我不知道我錯在哪裏。下面的代碼會進行排序,但只有前兩個條目。在Python中排序字典

請諮詢

scorecard ={} 
result_f = open("results.txt") 

for line in result_f: 
    (name,score) =line.split() 
    scorecard[score]=name 

for each_score in sorted(scorecard.keys(),reverse =True): 
    print('Surfer ' + scorecard[each_score]+' scored ' + each_score) 

result_f.close() 
+2

你要我們診斷這個不知道輸入和輸出? –

回答

3

我的猜測是你將分數保持爲字符串而不是整數。字符串不像整數那樣排序。考慮:

>>> sorted(['2','10','15']) 
['10', '15', '2'] 
>>> sorted([2, 10, 15]) 
[2, 10, 15] 

另一方面:你從分數映射到衝浪者 - 映射應該是相反的。否則,你將無法存儲兩個相同分數的衝浪者。

有了改變到反向映射和處理得分爲整數:

s = '''Fred 3 
John 10 
Julie 22 
Robert 10 
Martha 10 
Edwin 9''' 

scorecard = {} 
for line in s.split('\n'): 
    name, score = line.split() 
    scorecard[name] = score 

keyfunc = lambda item: (int(item[1]), item[0]) # item[1] is cast to int for sorting 
for surfer, score in sorted(scorecard.items(), key=keyfunc, reverse=True): 
    print '%-8s: %2s' % (surfer, score) 

結果:

Julie : 22 
Robert : 10 
Martha : 10 
John : 10 
Edwin : 9 
Fred : 3 

如果你想按降序排列變化按字母順序排列的名字和分數keyfunckeyfunc = lambda item: (-int(item[1]), item[0])並從sorted刪除reverse=True

有了這些變化,其結果是:

Julie : 22 
John : 10 
Martha : 10 
Robert : 10 
Edwin : 9 
Fred : 3 
+0

你使用的Python版本是什麼? –

+0

它工作在2.7版本不在3 –

+0

Python 2.6.6(r266:84297,2010年8月24日,18:46:32) –

2

我猜你的輸入文件包含像

cory 5 
john 3 
michael 2 
heiko 10 
frank 7 

線在這種情況下,你必須得分值轉換爲整數來正確地分類:

scorecard ={} 
result_f = open("results.txt") 

for line in result_f: 
    (name,score) =line.split() 
    scorecard[int(score)]=name 

for each_score in sorted(scorecard.keys(),reverse =True): 
    print('Surfer ' + scorecard[each_score]+' scored ' + str(each_score)) 

result_f.close() 
+3

另外,如果多個條目具有相同的分數,那麼將這些值存儲在類似的字典中將會中斷。 –

+0

@Frank我嘗試了你的方法,但後來我得到下面的錯誤打印('衝浪'+記分卡[each_score] +'得分'+ each_score) TypeError:不能將'int'對象隱式轉換爲str –

+0

@Winston good點。將牢記在心。 –

1

如果兩個名字可能具有相同的分數,也許只是將計分卡存儲爲列表:

scorecard = [] 
with open("results.txt") as result_f: 
    for line in result_f: 
     name,score = line.split() 
     scorecard.append((score,name)) 

for score,name in sorted(scorecard,reverse =True): 
    print('Surfer ' + name +' scored ' + str(score)) 
+0

我不能,我目前正在做這個來學習python中的dict。從書中讀取,似乎沒有任何工作:( –