Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort float in list of lists in Python?

I am trying to sort a nested list structure based on the last values of each nested lists. My list looks like this:

li = [['a1', 1, 1.56], ['b3', '6', 9.28], ['c2', 1, 6.25]...]

The output I would like is:

['b3', '6', 9.28]
['c2', 1, 6.25]
['a1', 1, 1.56]

I have tried a few solutions that haven't worked using itemgetter like this:

 rank_list = [i.sort(key=itemgetter(2)) for i in li]

What am I doing wrong? Is there a better way to sort nested lists? I get an AttributeError: 'str' object has no attribute 'sort'. Thanks for the help.

like image 755
drbunsen Avatar asked Jun 08 '26 16:06

drbunsen


1 Answers

You're close with one of your approaches, but what you actually want is this:

li.sort(key = itemgetter(2), reverse = True)
like image 178
g.d.d.c Avatar answered Jun 11 '26 04:06

g.d.d.c