5

I am a python beginner--headbangin'. This is a very basic question and I can't seem to find any straight forward answer, either using google or StackOverFlow.

QUESTION: I have a nested list:

 l = [
 [1,4,3,n]
 [2,2,4,n]
 [3,1,5,n]
 ]

I want to sort the entire list by the second value smallest to largest. I will end up sorting the list again by the third value... and nth value of each nested list.

HOW WOULD ONE SORT based on the SECOND, THIRD, Nth value?

A key is mentioned, but "key=lambda" is often used and that just confuses me more.

EDIT: Thank you guys for your help. I was able to use your advice to solve the problem at hand. I would upvote you but apparently, I can't yet show my thanks in that form. I will return someday and give you your reputation bumps.

2 Answers2

6

Can also be done using operator

Inside operator.itemgetter(1) you are indicating which index you want to sort on. So, in in this case we are specifying 1 which is the second item.

import operator

l = [[1,4,3], [2,2,4], [3,1,5]]
print(sorted(l, key=operator.itemgetter(1)))

output:

[[3, 1, 5], [2, 2, 4], [1, 4, 3]]
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • This even works on multiple nested lists. Thank you for your answer. If you could upvote my question, it will help me reciprocate faster. –  Oct 26 '15 at 16:39
5

You can try like this,

>>> l = [[1,4,3], [2,2,4], [3,1,5]]
>>> sorted(l, key=lambda x: x[1])
[[3, 1, 5], [2, 2, 4], [1, 4, 3]]

or:

>>> l.sort(key=lambda x: x[1])
>>> l
[[3, 1, 5], [2, 2, 4], [1, 4, 3]]
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
  • http://stackoverflow.com/questions/13669252/what-is-key-lambda It appears that lambda is on the fly function creator. Which is pretty cool once you understand what is going on. Thank you for your help. Could you please upvote my question so I can reciprocate in the future? –  Oct 26 '15 at 16:34