user381261 user381261 - 3 months ago 20
Python Question

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 o 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?

Answer

Pass the key argument.

L.sort(key=operator.itemgetter(1))