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]]
1

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.