2014-02-18 18 views
-1

,所以我需要一些高分到進行排序,這裏是我的代碼已經有:保持名稱和得分一起排序時

def sortscores(): 
    namelist = [] 
    scorelist = [] 
    hs = open("hst.txt", "r") 
    hscounter = 0 
    for line in hs: 
     if counter%2 !=0: 
      name = line 
      othername = name[0:len(name)-1] 
      namelist.append(othername) 
     else: 
      scorelist.append(int(line)) 

這使姓名和分數到列表所以現在我需要有他們排序,但我不能使用.sort()函數,因爲我必須自己寫這種排序,所以任何人都可以告訴我,我會怎麼做? (同時保持名稱與正確的得分的分值爲降序排列)

+1

爲什麼你寫的排序你自己?這是功課嗎? – kindall

+2

實現衆所周知的[排序算法]之一(http://en.wikipedia.org/wiki/Sorting_algorithm)。 – 2rs2ts

+0

@kindall是啊,我試過儘可能多的自己研究,並且無法找到如何在python中完成它,我問我的老師,他說這個算作研究 – RyanH2796

回答

0

,你可以讓你的字典的副本,發現最大的價值,關鍵保存到列表,從字典中刪除鍵,然後做直到複製的字典爲空。

import copy 

scores = {'hawks': 23, 'eagles': 42, 'knights': 33, 'rabbits': 44} #this or read from .txt 
scorescopy = copy.deepcopy(scores) #makes a copy of the dict, so you don't change the dict when deleting keys from the copy 
rank = [] #the list in which we want the keys ranked by value 

def keywithmaxval(scores): #finde the key with the highest value (stolen from another stackoverflow question) 
    values = list(scores.values()) 
    keys = list(scores.keys()) 
    return keys[values.index(max(values))] 

while len(scorescopy) > 0: #repeats until copy of dict is empty 
    maxkey = keywithmaxval(scorescopy) 
    scorescopy.pop(maxkey) #deletes key from copy of dict 
    rank.append(maxkey) #puts key in the ranked list 

print 'rank', rank #list of keys ranked by value 
print 'copy of dict', scorescopy #copy of dict, should be empty after we looped trough 
print 'original dict',scores #original dict, should be unchanged 

print '\nRank:' 
for key in rank: print key,':',scores[key] #pretty list of keys and vals 
2

如果您保存您的高分在(name, score)元組,那麼你可以很容易地讓他們在一起。由於您需要自己編寫排序函數,因此查看在其他問題中使用元組的示例可能會有所幫助。這裏有一個例子,簡單地找到最高分,同時保持名稱和分數。

首先設置數據。您可以使用zip這個

names = ['John', 'Jane', 'Tim', 'Sara'] 
scores = [100, 120, 80, 90] 
data = list(zip(names, scores)) # For Python 2.X you don't need the 'list' constructor 
print(data) 

輸出:

[('John', 100), ('Jane', 120), ('Tim', 80), ('Sara', 90)] 

現在發現的最大項:

max_entry = ('', 0) 
for entry in data: 
    if entry[1] > max_entry[1]: 
     max_entry = entry 

print(max_entry) 

輸出:

('Jane', 120)