1

I'm using CSV to sort the players highest sore. I have the name and scores in a list like this:

['4', 'Score One']
['8', 'Score Two']
['6', 'Score Three']

Which has been created from looping through the file, finding the maximum score and making a new list with this score and the player name.

for row in reader:
        highscores = ([row[-1], row[0]])

When I print (sorted(highscores)) the same list is returned to me. What I want it to sort as is:

['8', 'Score Two']
['6', 'Score Three']
['4', 'Score One']

If someone could explain to me why sorted doesn't work and what I could do to fix it, that'd be great.

Joseph
  • 39
  • 1
  • 1
    highscore is gettinng overwriten each iteration, is that intentional? – amit Mar 23 '16 at 21:43
  • Yeah, agreed, I thought that was a different one… [How to sort (list/tuple) of lists/tuples?](http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples), – poke Mar 23 '16 at 21:43
  • 1
    For clarification, what data structure is `highscores`? Is it a two-dimensional list or a list of tuples? Aka, does it look like `[('8', 'Score Three'),('6', 'Score Three'),('4', 'Score One')]` or like `[['8', 'Score Three'],['6', 'Score Three'],['4', 'Score One']]`? – s.py Mar 23 '16 at 21:45
  • 1
    why are you calling sorted on the list with two elements? – Padraic Cunningham Mar 23 '16 at 21:45

1 Answers1

2

Your problem is that each element of highscores is actually a list of strings, not a number. These rows do not have a useful ordering.

Use the key argument to sorted, to get an integer score from each row:

>>> highscores = [['4', 'Score One'],
['8', 'Score Two'],
['6', 'Score Three']]
>>> sorted(highscores, key=lambda x: int(x[0]))
[['4', 'Score One'], ['6', 'Score Three'], ['8', 'Score Two']]
wim
  • 266,989
  • 79
  • 484
  • 630
  • 1
    True but the list should not be the same after sorted was called, it would sort the current list correctly, it only gets weird when you have double digits and up – Padraic Cunningham Mar 23 '16 at 21:47
  • You are correct, I have edited the wording to clarify... better? – wim Mar 23 '16 at 21:48