I have 2d array, dimension 3x10, and I want to sort by values in 2nd row, from lowest to highest value.
This is a little function I wrote for this purpose:
def sorted_table(data, column=0, reverse=False):
return sorted(data, cmp=lambda a,b: cmp(a[column], b[column]), reverse=reverse)
Actually, I had a bit more complex requirement, which is to sort the table by two columns. It turns out that the cmp() function is quite versatile; this is my original function:
def sort_report(data):
"""Sort report columns: first by value, then by label."""
return sorted(data, cmp=lambda a,b: cmp(b[2], a[2]) or cmp(a[0], b[0])) # label is column 0; value is column 2
The b and a are reversed in the first case, since the goal was to sort the values fro higher to lower.