How to sort multidimensional array by column?
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.
sorted(list, key=lambda x: x[1])
Note: this works on time variable too.
You can use list.sort
with its optional key
parameter and a lambda
expression:
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=lambda x:x[1])
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
This will sort the list in-place.
Note that for large lists, it will be faster to use operator.itemgetter
instead of a lambda
:
>>> from operator import itemgetter
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=itemgetter(1))
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
You can use the sorted method with a key.
sorted(a, key=lambda x : x[1])