简体   繁体   中英

How can I sort a text file of winners' scores in order to print the top 5 winners?

I am very new to coding. I am currently creating a dice game where players roll their die in 5 rounds, and the player who score the most points in total is the winner. I am able to write the Score and the player name in an external file, "Winners.txt" and it looks like:

25 - Hisham

20 - Jonothan

30 - Hi

28 - Lo

26 - Jonothan

32 - Hello

Is there anyway I can reorder the list so the score is descending? And how can I then print the top 5 winners? Thanks

You can do the following:

with open('Winners.txt') as f:
    l=f.readlines() #read the file and save lines to list
   
l=[i.split() for i in l] #split lines
l=[ i for i in l if i!=[]] #remove empty lines
l.sort(key=lambda x: int(x[0]), reverse=True) #sort lines by number descending

result=l[:5] #get the first 5

for i in result:
    print(i[0], i[-1]) #print first and last items of each line

Output:

32 Hello
30 Hi
28 Lo
26 Jonothan
25 Hisham

We'll need your code if you wish to make modifications in it only. Assuming that you just need to sort the names based on score, here's the code

file =open('winners.txt')
winner= file.read().split()
dictWin = {}

del winner[1::3]           #deletes '-' symbol

for i in range(0,len(winner),2):
    dictWin[winner[i]]=winner[i+1]

print(dictWin[max(dictWin.keys())])

You can use dictWin to get more specific data such as lowest score and rewrite sorted data in winners.txt

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.

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