0

I am writing some code to take high score data from an external file, take the top 5, and display them. I am nearly there, but my code only takes the first digit of the high score, so scores like 12 are seen to be smaller than scores like 8. Is there a way to take the whole number into consideration when sorting?

My external .txt file looks like this:

('Louis', 18)
('Louis', 4)
('Louis', 2)
('Louis', 4)
('Troy', 0)
('Andre', 6)
('Louis', 1)
('Louis', 17)
('Louis', 3)
('Louis', 9)

and the output looks like this:

('Louis', 9)
('Andre', 6)
('Louis', 6)
('Louis', 4)
('Louis', 4)

This is my code:

with open('highscore.txt', 'r') as score_file:
    scores = [line.split(' ') for line in score_file]
scores.sort(key=lambda x: x[1], reverse=True)

print('The highscores are...\n')

for i in range(0, 5):
    print(' '.join(scores[i]))
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 4
    You are sorting the numbers as strings and that sorts lexicographically. – quamrana Oct 11 '22 at 19:51
  • That's not "taking the first digit". That's how numbers sort if you sort them as strings. If you have numbers, then convert them to integer before scoring. Or, use `lambda x: int(x[1])`. – Tim Roberts Oct 11 '22 at 19:52
  • 1
    Welcome to Stack Overflow. Please try to [debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) code before asking a question, in order to make sure you *understand* the problem as well as possible. If you are writing code at this level in the first place, you should have the skills needed to find out that the score values are strings rather than integers; this allows for asking the actual **question**, i.e., how to get integers instead. – Karl Knechtel Oct 11 '22 at 20:07

2 Answers2

2

Use ast.literal_eval() to parse each line of the file. This will parse the numbers as integers, not strings.

import ast

with open('highscore.txt', 'r') as score_file:
    scores = [ast.literal_eval(line) for line in score_file]
scores.sort(key=lambda x: x[1], reverse=True)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

your data is extracted from the file as strings and you want numbers

#    scores = [
#        ('Louis', '18'),
#        ('Louis', '4'),
#        ('Louis', '2'),
#        ('Louis', '4'),
#        ('Troy', '0'),
#        ('Andre', '6'),
#        ('Louis', '1'),
#        ('Louis', '17'),
#        ('Louis', '3'),
#        ('Louis', '9'),
#    ]

with open('highscore.txt', 'r') as score_file:
    scores = [line.split(' ') for line in score_file]

scores.sort(key=lambda x: -int(x[1]))
Zhihar
  • 1,306
  • 1
  • 22
  • 45