-5

I'm in the middle of making a leaderboard, currently I am taking data from a txt file and dumping it into a list.

The list's format looks something like this:

[['56', 'UsernameA'], ['73', 'UsernameB'], ['52', 'UsernameC'], ['10', 'UsernameD']]

I would like to create a leaderboard, therefore I would like to sort the list from the highest number to the lowest, I've tried using the sort() function, however this only works on integers and my list contains the username and the score, so I cannot convert it into an integer, unless I'm completely wrong here.

PyTest
  • 1
  • 1

1 Answers1

0

You are correct, you can use the sorted() function or .sort() method.

I can see two options to sort in the way you want; both required basing the sort on the first element of the sub-lists; which must be converted to integers.

You can then either base it directly on this heuristic, but then you will have to use reverse=True as an argument to the function so that you get highest to lowest sorting. Or, you can just use a little hack and sort based on the negative of each of these integers :).

l = [['56', 'UsernameA'], ['73', 'UsernameB'], ['52', 'UsernameC'], ['10', 'UsernameD']]
l.sort(key=lambda j: -int(j[0]))

which modifies l to:

[['73', 'UsernameB'], ['56', 'UsernameA'], ['52', 'UsernameC'], ['10', 'UsernameD']]
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54