[英]How to sort a list of scores in 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'
任何想法如何解决这个问题,这意味着什么以及我接下来可以做什么?
这应该可以很好地完成这项工作,如果有什么不明白的地方,请随时提问;
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.