分类时把名字和分数放在一起

2024-10-01 11:24:32 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我需要把高分排序,下面是我已经掌握的代码:

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()函数,因为我必须自己编写排序,所以有人能告诉我如何进行排序吗?(将分数按降序排序,同时保持名字的正确分数)


Tags: 代码name排序deflineopen名字分数
2条回答

您可以复制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

如果您将高分存储在(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)

输出:

^{pr2}$

现在找到最大条目:

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

print(max_entry)

输出:

('Jane', 120)

相关问题 更多 >