排序时将姓名和分数保持在一起 [英] Keeping name and score together while sorting

查看:156
本文介绍了排序时将姓名和分数保持在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要对一些高分进行排序,这是我已经拥有的代码:

so I need to sort some high scores into order and here is the code I already have:

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()函数,所以有人可以告诉我该怎么做吗? (将分数按降序排列,同时保留名称正确的分数)

This puts the names and scores into lists so now I need to have them sorted but I can't use the .sort() function because I have to write the sort myself so can anyone tell me how I would do this? (sort the scores into descending order whilst keeping the names with the correct scores)

推荐答案

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

If you store your high scores in (name, score) tuples, then you can easily keep them together. Since you need to write the sort function yourself, it might be helpful to look at an example of using tuples in another problem. Here's an example of simply finding the maximum score while keeping the name and scores together.

首先,设置数据.您可以为此使用zip

First, set up the data. You can use zip for this

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)

这篇关于排序时将姓名和分数保持在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆