如何在Python中对分数列表进行排序?

2024-09-26 22:50:29 发布

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

我有一个这样的分数列表:

 Username Tom, Score 7
 Username Tom, Score 13
 Username Tom, Score 1
 Username Tom, Score 24
 Username Tom, Score 5

我想对列表进行排序,使其处于前5位,然后截断列表以删除不在前5位的列表,然后打印此前5位

到目前为止,我的代码是:

   scores = [(username, score)]
        for username, score in scores:
            with open('Scores.txt', 'a') as f:
                for username, score in scores:
                    f.write('Username: {0}, Score: {1}\n'.format(username, score))
                    scoreinfo = f.split()
                    scoreinfo.sort(reverse=True)

这是我到目前为止所得到的,这是我得到的错误:

Traceback (most recent call last):
   File "Scores.txt", line 92, in <module>
     songgame()
   File "Scores.txt", line 84, in songgame
     scoreinfo = f.split()
 AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

有没有办法解决这个问题,它意味着什么,我下一步能做什么


Tags: intxt列表forlineusernamefilesplit
2条回答

这项工作应该做得很好,如果有什么你不明白的,尽管问

scores = [('Tom', 7), ('Tom', 13), ('Tom', 1), ('Tom', 24), ('Tom', 5)]

scores.sort(key=lambda n: n[1], reverse=True)
scores = scores[:5]  # remove everything but the first 5 elements

with open('Scores.txt', 'w+') as f:
    for username, score in scores:
        f.write('Username: {0}, Score: {1}\n'.format(username, score))

运行程序后Scores.txt如下所示:

Username: Tom, Score: 24
Username: Tom, Score: 13
Username: Tom, Score: 7
Username: Tom, Score: 5
Username: Tom, Score: 1

我不太清楚你的清单上到底是什么东西。这是另一个文件吗?它是python对象吗?我认为这是一个类似python的列表

scores = [("Tom", 7), ("Tom", 13), ("Tom", 1), ("Tom", 24), ("Tom", 5)]

我对你的代码做了一些修改。我开始用scores.sort()函数的第二个对象对这个列表进行排序。如果它已排序,您只需将其写入您的文件中

def your_function(top_list=5):
    scores = [("Tom", 7), ("Tom", 13), ("Tom", 1), ("Tom", 24), ("Tom", 5)]
    scores.sort(key=lambda score: score[1], reverse=True)

    with open('Scores.txt', 'w') as f:
        for i in range(top_list):
            username, score = scores[i]
            f.write('Username: {0}, Score: {1}\n'.format(username, score))

相关问题 更多 >

    热门问题