Yes. The sorted built-in accepts a key argument:
sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]
note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).
or alternatively,
from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]
Read more on the python wiki.
Answer from roippi on Stack OverflowYes. The sorted built-in accepts a key argument:
sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]
note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).
or alternatively,
from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]
Read more on the python wiki.
You can use the sorted method with a key.
sorted(a, key=lambda x : x[1])
How to sort a 2D array in descending or ascending order by a column?
How to Sort Arrays by the nth Column in Python? - Data Exploration & Visualization - Data Science Dojo Discussions
How would you sort a 2D list by row based on the first column using a separate list as a key
Sorting 2d Array
I'm trying to found a way to order a 2D array that is like this:
Data[0][0]="String" Data[0][1]=3 etc.
What I can do? Thank you in advance for any reply.
so i have a data set of rain data over the course of a year where it ends up being formatted into something like this except its a lot longer
[['Nov', 0.0], ['Nov', 0.0], ['Nov', 0.09],['Feb', 0.0], ['Feb', 0.0], ['Feb', 0.09],['Oct', 0.56], ['Oct', 0.0], ['Oct', 0.03], ['Oct', 0.62]]
now I figured I would need another list to function as a lookup to help sort this data by month according to calendar order so I made one
month_lookup = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
but now I am a tad confused about how I would go about using something like the sorted() function to use the lookup as the way to sort the 2D list above