This function allows you to easily sort a list by multiple columns in ascending and descending orders similar in function to the ORDER BY clause in SQL.
1 2 3 4 5 6 7 8 9
def orderBy(sortlist, orderby=, desc=): '''orderBy(sortlist, orderby, desc) >> List sortlist: list to be sorted orderby: list of field indexes desc: list of field indexes that are to be sorted descending''' orderby.reverse() for i in orderby: sortlist.sort(lambda x, y: cmp(*[(x[i], y[i]), (y[i], x[i])][i in desc])) return sortlist
Imagine you have a list:
New = [[1, 50.00, 'Bob'], [4, 50.00, 'Mary'], [3, 500.00, 'Tom'], [5, 75.00, 'Tracy'], [7, 175.00, 'Linda'], [2, 75.00, 'Charles']]
Now imagine this list is a SQL table (with fields called Loans, Amount, Name) and you want them in a particular order You might say:
SELECT * FROM New ORDER BY Amount DESC, Loans, Name
We are asking for the Amount field to be sorted in descending order.
To duplicate this using the above function:
NewList = orderBy(New, [1, 0, 2], )