HighwayJohn HighwayJohn - 2 months ago 15
Python Question

Sorting a nested string list for the second element (python)

I have the following problem. I have a nested list which contains football scores and their odds like it is shown in this short example.

scoreresultlist = [('1:0', '23.00'), ('0:0', '12.50'), ('0:1', '10.00'),('2:0', '36.00'),
('1:1', '9.50')]


Now I would like to sort the scores according to their odds. My problem is, that it is a nested list and all entries are saved as strings. Hope you can help and thanks in advance!

Answer Source

What you're really asking is to sort an array of tuples by their second element, which you can do by:

sorted_list = sorted(scoreresultlist, key=lambda element: Decimal(element[1]))

If you want to sort it in place, you can do

scoreresultlist.sort(key=lambda element: Decimal(element[1]))

(The Decimal(element[1])) type casts the string element to a Decimal for sorting purposes but does not modify the list.)