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], )
and in Python 2.4.
please explain. can you please explain the code which Steve Lucy has written. what is the use of * how is the cmp function working inhis code thanks
The * causes the tuple we choose, (x[i], y[i]) or (y[i], x[i]), to be mapped to the function's arguments, instead of being passed as a single argument (i.e., cmp(x[i], y[i]) and not cmp((x[i], y[i]))
Let's say you have a function:
and a list of values you want added:
instead of saying something like:
You could say: