繁体   English   中英

如何仅显示文件中的前 5 个高分?

[英]How do I display just the top 5 highscores from my file?

这是带有分数的文件:

Ishaan - 72
Jack - 84
Bob - 23
Louis - 77
Arnav - 56
Ben - 48
Ted - 39

到目前为止,我已经对文件进行了排序,但我不知道如何只显示文件中的前 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]))

这也与您之前的问题具有相同的答案,但已修改:

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]

因此,如果您的排序列表是list1

top5 = list1[:5]

如果您使用的是 lambda:

ScoresWithNames.sort(key=lambda x: int(x.split(" - ")[-1]),reverse = True)
print(ScoresWithNames[:5])

现在如果你想用换行符打印它,你有两种方法:

for i in top5:
    print(i)

或者:

print('\n'.join(i for i in top5)) # or scoreswithnames 

获得 5 个最高分的简单方法是使用来自collections.Countermost_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:

[('Jack', 84), ('Louis', 77), ('Ishaan', 72), ('Arnav', 56), ('Ben', 48)]

如果您希望您的分数重新格式化为"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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM