9

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?

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
njvb
  • 1,377
  • 3
  • 18
  • 36

3 Answers3

22

Pass the key argument.

L.sort(key=operator.itemgetter(1))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    I don't think I've used `sort` since we got `sorted`. But `operator.itemgetter` is better than writing your own lambda. – oylenshpeegul Mar 05 '11 at 02:40
  • 1
    @oylenshpeegul: I'm genuinely curious. Why is operator.itemgetter superior? My instinct is to write the lambda. It's shorter, more general-purpose, and doesn't require an import of a module I seldom use. itemgetter seems to be 30% faster or so, I admit, but it's unlikely this'll be a bottleneck in real code. – DSM Mar 05 '11 at 03:12
  • 1
    well I actually have to sort a list of numbers I parsed out of a file with 1.8 mil entries so the 30% speed up is appreciated in my case. – njvb Mar 05 '11 at 03:19
  • x = [[[5,3],1.0345],[[5,6],5.098],[[5,4],4.89],[[5,1],5.97]] With a list like this is can we sort using `itemgetter()` with respect to elements in x[0][1] ? – nidHi Dec 02 '16 at 09:45
  • what is "operator" over here?? – Sssssuppp Oct 22 '19 at 22:24
13
>>> 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]]
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
  • x = [[[5,3],1.0345],[[5,6],5.098],[[5,4],4.89],[[5,1],5.97]] With a list like this is, how can we sort with respect to elements in x[0][1] ? – nidHi Dec 02 '16 at 09:46
3

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.

Andrew White
  • 52,720
  • 19
  • 113
  • 137