Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to sort a list of lists?

I have a list of lists (can't be tuples since I have to generate it dynamically) and it is structured as a list of lists of one int and one float Like so:

[[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]

I want to get it sorted but I have only managed to get the built in sorting function to sort it by the first element of the lists or not do anything, but I need to sort them by the second element of the list and I don't want to implement my own sorting function. So an example of what I would want is:

[[1,1.0345],[3,4.89],[2,5.098],[2,5.97]]

Could someone tell me how to get one of the built in sorting functions to do this?

like image 525
njvb Avatar asked Mar 05 '11 02:03

njvb


People also ask

Can I sort a list of lists?

Use the sort() Function to Sort a List of Lists in Python. The sort() method sorts the list of lists in Python according to the first element of each inner list. This method makes changes in the original list itself. We use the reverse parameter to sort in descending order.

How do I sort a nested list?

There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.


3 Answers

>>> l = [[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
>>> l.sort(key=lambda x: x[1])
>>> l
[[1, 1.0345], [3, 4.8899999999999997], [2, 5.0979999999999999], [2, 5.9699999999999998]]
like image 124
Senthil Kumaran Avatar answered Oct 30 '22 14:10

Senthil Kumaran


Pass the key argument.

L.sort(key=operator.itemgetter(1))
like image 35
Ignacio Vazquez-Abrams Avatar answered Oct 30 '22 12:10

Ignacio Vazquez-Abrams


How about using they key parameter of sorted...

sorted_list = sorted([[1,1.0345],[3,4.89],[2,5.098],[2,5.97]], key=lambda x: x[1])

This tells python to sort the list of lists using the item at index 1 of each list as the key for the compare.

like image 20
Andrew White Avatar answered Oct 30 '22 12:10

Andrew White