Kit Fullman
Kit Fullman

Reputation: 29

Sorting a mixture of single digit and double digit numbers

I'm making a game where you guess a song from it's artist and some letters provided. I want to create a high scores list, however, I'm finding this difficult as when I have scores such as 9 & 12, python sorts 9 higher than 12 because 1< 9. I would like some help with this if that's OK.

print('Score: ' + str(score))
name = input('Enter your name: ')

scoreAppender.append(str(score))
scoreAppender.append(name)
scoresData = '-'.join(scoreAppender)
print(scoresData)

scoresfile = open('scores.txt', 'a')
scoresfile.write(scoresData + '\n')
scoresfile.close()

scoresfile = open('scores.txt', 'r')

scoresList = []

for score in scoresfile:
    scoresList.append(score)

scoresList.sort(key = lambda x: x.split('-')[0])

for score in scoresList:
    print(score)

scoresfile.close()

Upvotes: 2

Views: 5990

Answers (2)

Torxed
Torxed

Reputation: 23480

If I were allowed to go rock-n-roll on your code, I'd do something along the lines of:

import operator

score = 10 # for instance

print(f'Score: {score}')
name = input('Enter your name: ')

scoresData = f'{score}-{name}'
print(scoresData)

with open('scores.txt', 'a') as database: # yea i know
    database.write(scoresData + '\n')

# ---
scoresList = {}
with open('scores.txt', 'r') as database:
    for row in database:
        score, player = row.split('-', 1)
        scoresList[player.strip('\n')] = int(score) # Remove \n from the player name and convert the score to a integer (so you can work on it as an actual number)

for row in sorted(scoresList.items(), key=operator.itemgetter(1)): # Sort by the value (item 1) of the dictionary
    print('Player: {} got a score of {}'.format(*row))

The sorting is a courtesy of [A]How do I sort a dictionary by value?
And if you want to go real fancy you can do:

import pickle
...
with open('scores.db', 'wb') as database:
    pickle.dump(scoreList, database)

or to load the values in again:

with open('scores.db', 'rb') as database:
    scoreList = pickle.load(database)

Which eliminates the need to parse a text-file. You don't have to worry about doing player.strip('\n') because there won't be any newlines etc to handle. The down side of doing a memory dump via pickle, is that i's a "memory dump", meaning editing values in place is not exactly possible/straight forward.

Another good solution would be to use sqlite3, however - it gets pretty complicated rather fast if you're not used to working with databases. If you're up for it tho, that's your absolutely best route long term.

Upvotes: 0

Vikrant Sharma
Vikrant Sharma

Reputation: 419

Just convert to int in your sort key lambda:

scoresList.sort(key = lambda x: int(x.split('-')[0]))

Upvotes: 2

Related Questions