How to sort a list of lists?

I have a list of lists (there cannot be tuples, since I have to generate it dynamically), and it is structured as a list of lists of one int and one float. Thus:

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

I want it to be sorted, but I managed to get a built-in sort function to sort by the first element of the lists or do nothing, but I need to sort them by the second element of the list and I do not want to implement my own sort function. So, an example of what I want is:

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

Can someone tell me how to make one of the built-in sort functions for this?

+8
python sorting list
source share
3 answers

Pass the key argument.

 L.sort(key=operator.itemgetter(1)) 
+18
source share
 >>> 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]] 
+10
source share

How about using their key parameter 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 element in index 1 of each list as a key to compare.

+1
source share

All Articles