[英]How do I display just the top 5 highscores from my file?
This is the file with the scores:这是带有分数的文件:
Ishaan - 72
Jack - 84
Bob - 23
Louis - 77
Arnav - 56
Ben - 48
Ted - 39
So far I have sorted the file but I don't know how to display just the top 5 scores from the file.到目前为止,我已经对文件进行了排序,但我不知道如何只显示文件中的前 5 个分数。
ScoresFile2 = "/Users/KADAM BOYS/Desktop/Ishaan's Folder/Homework (Year 10)/Computing/Mock Project/Scores.txt"
ScoresWithNames = []
with open(ScoresFile2) as file2:
for line in file2:
ScoresWithNames.append(line.strip())
ScoresWithNames.sort(key=lambda x: int(x.split(" - ")[-1]))
This also has the same answer as your previous question, but modified:这也与您之前的问题具有相同的答案,但已修改:
l = ['Ishaan - 72', 'Jack - 84', 'Bob - 23', 'Louis - 77']
[' - '.join(k for k in j[::-1]) for j in sorted([i.split(' - ')[::-1] for i in l],reverse = True,key=lambda x: int(x[0]))][:5]
So if your sorted list is list1
:因此,如果您的排序列表是list1
:
top5 = list1[:5]
If you are using lambda:如果您使用的是 lambda:
ScoresWithNames.sort(key=lambda x: int(x.split(" - ")[-1]),reverse = True)
print(ScoresWithNames[:5])
Now if you want to print it with a new-line, you have two ways:现在如果你想用换行符打印它,你有两种方法:
for i in top5:
print(i)
or:或者:
print('\n'.join(i for i in top5)) # or scoreswithnames
An easy way to get the 5 highest scores is with most_common
from collections.Counter
:获得 5 个最高分的简单方法是使用来自collections.Counter
的most_common
:
from collections import Counter
with open("data.txt") as f:
counts = Counter()
for line in f:
name, score = line.split(" - ")
counts[name] += int(score)
print(counts.most_common(5))
Output: Output:
[('Jack', 84), ('Louis', 77), ('Ishaan', 72), ('Arnav', 56), ('Ben', 48)]
If you want your scores formatted back into "name - score"
format:如果您希望您的分数重新格式化为"name - score"
格式:
print([f"{name} - {score}" for name, score in counts.most_common(5)])
# ['Jack - 84', 'Louis - 77', 'Ishaan - 72', 'Arnav - 56', 'Ben - 48']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.