6

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]]
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
  • 5
    There is a similar question here [How to sort (list/tuple) of lists/tuples?][1] [1]: http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples – Hooting Aug 21 '15 at 05:16

1 Answers1

9

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]]
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65