Complex 'compare'

Frank Millman frank at chagford.com
Wed Dec 26 01:17:52 EST 2018


"Frank Millman"  wrote on 2018-12-18 in message news:...
>
> 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 know this is of minor interest, but I have refined my function and it 
looks much neater now, so I thought I would share it.

def compare(source_row, target_row, order):

    # 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

    LT, EQ, GT = -1, 0, 1

    for pos, desc in order:
        source_col = source_row[pos]
        target_col = target_row[pos]
        if desc:
            less_than = False if source_col is None else source_col > 
target_col
        else:
            less_than = True if source_col is None else source_col < 
target_col
        if less_than:
            return LT
        if new_data != col_data:
            return GT
        # must be EQ - continue with next sort column
    return EQ  # if we get here, all sort columns compare equal





More information about the Python-list mailing list