0

If anybody could assist me that would be great. I've been trying to print a high scores list and every method I've tried to sort the scores isn't working and I don't understand what I keep doing wrong.

def show_high_scores():
    """
    shows top 5 highest scores to the user
    """
    scores_col = SHEET.worksheet('high_scores').col_values(2)
    scores_data = scores_col[1:]
    sorted_scores = sorted(scores_data, reverse=True)

    names_col = SHEET.worksheet('high_scores').col_values(1)
    names_data = names_col[1:]

    print('\nHigh Scores\n')

    for i in range(5):
        print(str(names_data[i]) + "\t" + str(sorted_scores[i]))
AriRix1410
  • 23
  • 3
  • [edit] your question and add the values of `scores_col`, show the current results and the expected results. – Marco Aurelio Fernandez Reyes Apr 07 '22 at 17:23
  • @MarcoAurelioFernandezReyes The issue seems to be that the order only seems to take into account the first digit. So scores can appear as "9, 9, 7, 13, 10". I presume this is because the 1 in 13 is lower than the other numbers? – AriRix1410 Apr 07 '22 at 17:51

1 Answers1

0

The problem is that the scores_data is a list of strings, so sorted() will sort them alphabetically. As you've noticed, it sorts using the first digit of the number rather than the numeric value.

As explained in this answer, you can easily convert the list scores_data to integers using a list comprehension like this:

scores_numeric = [int(score_str) for score_str in scores_data]

Then you can just sort the new numeric array instead:

sorted_scores = sorted(scores_numeric, reverse=True)
Daniel
  • 3,157
  • 2
  • 7
  • 15