.sort(reverse = True)将10移到底部

时间:2018-07-03 02:49:42

标签: python sorting

您的分数是>>> 10

您想再次参加测验吗?是或否:n 5:帅哥

5:2qa3ws8ujhyi9; [] \']

2:zzzz

2:y

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 :(得分:0)

您可以记录分数并将其排序如下:

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))