.sort (reverse = True) переместится на 10 вниз - PullRequest
0 голосов
/ 03 июля 2018

Ваш счет >>> 10

Хотите снова пройти тест? Y или N: n 5: горячий

5: 2qa3ws8ujhyi9; [] \ ']

2: zzzz

2: у

10: ТЕСТ

До свидания!

template = """{score} : {name}"""
display_good = template.format(score=score,name=user_name)  
highscore_a = open("highscoreFile.txt",'a') #The file that keeps the highest scores of all time
highscore_a.write(display_good)
highscore_a.write('\n')
highscore_a.close()
highscore_r = open("highscoreFile.txt", "r") 

read_top_5 = highscore_r.readlines()
read_top_5.sort(reverse=True)
i =[5]

repeat = (read_top_5[-5:])
for i in repeat:
    print(i)    

1 Ответ

0 голосов
/ 03 июля 2018

Вы можете записать счет и отсортировать его следующим образом:

from pathlib import Path  # python3.6+
record_fmt = """{score} : {name}"""
record = record_fmt.format(score=score, name=user_name)  
record_path = Path("highscoreFile.txt")
with record_path.open('a') as fp:
    fp.write(f'{record}\n') 

records = record_path.read_text().strip().split('\n')
top_5 = sorted(records, key=lambda x: -int(x.strip().split(':')[0].strip()))[:5]
print('\n'.join(top_5))   
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...