簡體   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