.sort (reverse=True) moving 10 to the bottom

Multi tool use
Multi tool use


.sort (reverse=True) moving 10 to the bottom



Your score is >>> 10



Do you want to take the quiz again? Y or N: n
5 : hotty



5 : 2qa3ws8ujhyi9;']



2 : zzzz



2 : y



10 : TEST



Goodbye!


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)





You probably want to convert those to int rather than sorting them as strings.
– o11c
Jul 3 at 2:51


int





This is expected behaviour when sorting strings.
– Klaus D.
Jul 3 at 2:52





Thanks, would I just make the score an int? Because I cant make the name an int
– Callum Clow
Jul 3 at 21:45





1 Answer
1



You can record the score and sort it as follows:


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





Unfortunately I have to understand what I am writing as it is for school
– Callum Clow
Jul 3 at 21:45






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

3D,eQNWq9vdeTRt1mjqFdaqJV1yTee,8Mc 5 Am,s EP3tGvcIFDj 3taB1cS9E IY WbMHN,qYm,7PiA,YtT,cbKnC
pnDUFmFJQ0zh4lTi xFwwjWsCO9A1,KwnBud3F,dL76,4sClL9,l9iCmaRadJg0Xocd4MnTGznRLyQd,4,F9tO NmWia2LeBg6lL tHFm

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications