排序时保持名称和分数

时间:2014-02-18 16:34:21

标签: python list sorting file-io

所以我需要将一些高分排序为顺序,这是我已有的代码:

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()函数,因为我必须自己编写排序,所以任何人都可以告诉我如何做到这一点? (将分数按降序排序,同时保持名称与正确的分数)

2 个答案:

答案 0 :(得分:2)

如果您将高分存储在(name, score)元组中,那么您可以轻松地将它们保持在一起。由于您需要自己编写sort函数,因此查看在另一个问题中使用元组的示例可能会有所帮助。这是一个简单地找到最高分数同时保持名称和分数的例子。

首先,设置数据。您可以将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)

答案 1 :(得分:0)

你可以复制你的dict,找到最大值,将密钥保存到列表中,从dict中删除密钥然后再次执行,直到复制的dict为空。

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