Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: sorting a list by "column" [duplicate]

Tags:

python

sorting

How can I sort a list-of-lists by "column", i.e. ordering the lists by the ith element of each list?

For example:

a=[['abc',5],
   ['xyz',2]]

print sortByColumn(a,0)

[['abc',5],
 ['xyz',2]]

print sortByColumn(a,1)

[['xyz',2],
 ['abc',5]]
like image 735
Mark Harrison Avatar asked Aug 21 '15 05:08

Mark Harrison


1 Answers

You could use sort with its key argument equal to a lambda function:

sorted(a, key=lambda x: x[0])
[['abc', 5], ['xyz', 2]]

sorted(a, key=lambda x: x[1])
[['xyz', 2], ['abc', 5]]

Another way would be to use key with operator.itemgetter, which creates the required lambda function:

from operator import itemgetter
sorted(a, key=itemgetter(1))
[['xyz', 2], ['abc', 5]]
like image 194
The6thSense Avatar answered Nov 14 '22 23:11

The6thSense