Search code examples
pythonpython-2.7storagestoring-data

Python 2 Sorting from a text file


Im trying to write a code where user puts in their score (a number), and then they put in their name. both the score and name gets stored in a text file (alongside with '\n', so that every new couple gets stored on the new line).

            hscores = open("highscores.txt", "a")
            hscores.write(str(score))
            hscores.write(" ")
            hscores.write(nickname)
            hscores.write("\n")
            hscores.close()

then, I open the text file, take every input in there, sort it by highest to lowest and output it:

    hscores22 = open("highscores.txt", "r")
    listings2 = hscores22.readlines()
    sorting2 = sorted(listings2, reverse=True)
    print "|     1     | " + sorting2[0]
    print "|     2     | " + sorting2[1]
    print "|     3     | " + sorting2[2]
    print "|     4     | " + sorting2[3]
    print "|     5     | " + sorting2[4]
    print "|     6     | " + sorting2[5]
    print "|     7     | " + sorting2[6]
    print "|     8     | " + sorting2[7]
    print "|     9     | " + sorting2[8]
    print "|     10    | " + sorting2[9]

The problem is that python thinks that number that starts with the biggest number, is bigger, for example: 90>1000, 50>100 (I suppose thats because i have to convert all the numbers to strings before storing them in the text file). is there any way i could fix this? thanks in advance.


Solution

  • Since you're sorting strings, Python is comparing them lexicographically - so '2' is bigger than '1'. You need to extract the numeric part of your string, convert it to a number and use this number for sorting key:

    sorting2 = sorted(listings2, reverse=True, key=lambda x: int(x.split()[0]))
    

    BTW, next 10 lines really ask to be replaced by a for loop…