Reputation:
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.
Upvotes: 5
Views: 5699
Reputation: 21446
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]]
Upvotes: 5
Reputation: 26578
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]]
Upvotes: 6