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]]
解决方案
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]]