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.
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
:
top5 = list1[:5]
If you are using 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
:
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)]
If you want your scores formatted back into "name - score"
format:
print([f"{name} - {score}" for name, score in counts.most_common(5)])
# ['Jack - 84', 'Louis - 77', 'Ishaan - 72', 'Arnav - 56', 'Ben - 48']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.