Hi all
I want to compare two tuples. They each represent a row in a database, and
each element represents a column, so I will use that terminology.
I need to know if one row is greater than or less than the other. The sort
sequence can be complex - one or more columns, each of which can be sorted
ascending or descending.
Below is the function I have come up with. Can anyone see any problem with
it, or suggest a better way to do it?
I have taken one short cut. If all sort columns compare equal, it will
return True, which is wrong. In practice I ensure that one of the sort
columns will be the primary key, so the two rows should never be equal.
Thanks
Frank Millman
def compare(source_row, target_row, order, compare_type):
# source_row - the row I want to compare - some sort columns could
contain None
# target_row - the row I want to compare it with - no sort columns will
contain None
# order - a list of 2-part tuples defining the sort sequence - the
column number, and True if descending else False
# compare_type - either 'gt' or 'lt'
def compare_col(source_col, target_col, desc, compare_type):
if compare_type == 'gt':
if desc:
return True if source_col is None else source_col <
target_col
else:
return False if source_col is None else source_col >
target_col
elif compare_type == 'lt':
if desc:
return False if source_col is None else source_col >
target_col
else:
return True if source_col is None else source_col <
target_col
for pos, desc in order:
source_col = source_row[pos]
target_col = target_row[pos]
if compare_col(source_col, target_col, desc, compare_type):
return True
if source_col != target_col:
return False
# if we get here they are equal -
# compare the next column in the sort sequence
return True
--
https://mail.python.org/mailman/listinfo/python-list