-1

I'm doing a high score system for my code for coursework, I managed to sort my numbers with some help from here, but now i decided to add the names so the high scores correlate to a person, it doeskin sort it, this is my code so far:

player1=input("input")
player1score=int(input("input"))


highscore = open("Scores.txt", "r")
whowon=("{0}-{1}".format(player1score,player1))
highscores = highscore.readlines()
highscore.close()
highscore = open("Scores.txt", "a")
highscore.write(whowon)
highscore.write("\n")
highscore.close()
highscore = open("Scores.txt", "r")
highscores = highscore.readlines()

highscores = [ x.rstrip() for x in highscores ]
highscores.sort(reverse=True, key=int)

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]
top=("{0}\n{1}\n{2}\n{3}\n{4}\n".format(top1, top2, top3, top4, top5))


highscore.close()

highscore=open("Scores.txt", "w")
highscore.write(top)
highscore.close()


the file outputs

68-Dylan
45-Snones
70-Pedro

Is there a way i can separate the integer values, sort them, then put them back together respectively? The error code im getting for this is

highscores.sort(reverse=True, key=int)
ValueError: invalid literal for int() with base 10: '68-Dylan'
Rixu
  • 29
  • 3
  • Try this. Maybe this can solve your problem. https://stackoverflow.com/questions/32833226/python-how-do-you-sort-the-contents-of-a-txt-file-in-numerical-order – Rishabh K Sharma Feb 14 '20 at 10:47
  • I haven't tested your code locally in my editor but going through your code, I feel you can use a list of objects, each object carrying a score and name. You can sort this list against the score and basically output the score and name after sorting. – Krishna Tangirala Feb 14 '20 at 10:48

1 Answers1

2

Let's say this is your input string. You can use sorted, which takes a key argument to transform the data prior to sorting:

l = '''68-Dylan
45-Snones
70-Pedro'''.splitlines()

sorted(l, key=lambda x: int(x.split('-', 1)[0]))
# ['45-Snones', '68-Dylan', '70-Pedro']
yatu
  • 86,083
  • 12
  • 84
  • 139