So I have this list, we'll call it listA. I'm trying to get the [3] item in each list e.g. ['5.01','5.88','2.10','9.45','17.58','2.76']
in sorted order. So the end result would start the entire list over again with Santa at the top. Does that make any sense?
[['John Doe', u'25.78', u'20.77', '5.01'], ['Jane Doe', u'21.08', u'15.20', '5.88'], ['James Bond', u'20.57', u'18.47', '2.10'], ['Michael Jordan', u'28.50', u'19.05', '9.45'], ['Santa', u'31.13', u'13.55', '17.58'], ['Easter Bunny', u'17.20', u'14.44', '2.76']]
An anonymous
lambda
function is not necessary for this task. You can useoperator.itemgetter
, which may be more intuitive:If you want to return the complete list in sorted order, this may work. This takes your input list and runs
sorted
on top of it. Thereverse
argument set toTrue
sorts the list in reverse (descending) order, and thekey
argument specifies the method by which to sort, which in this case is thefloat
of the third argument of each list:If you only need the values in sorted order, the other answers provide viable ways of doing so.
And you are good to go. Using itemgetter() within a sort is extremely helpful when you have multiple indexs to sort on. Lets say you wanted to sort alphabetically on the first value in case of a tie you could do the following
And Voilà!
Try this: