我有一个这样的分数列表:
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
