Python分数清单

时间:2018-11-23 09:40:38

标签: python python-3.x

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

 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'

有什么想法可以解决这个问题,这意味着什么,我下一步可以做什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-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))