Programmatically Picking An Inequality Operator
I'm trying to perform actions based on input from a config file.  In the config, there will be specifications for a signal, a comparison, and a value.  I'd like to translate that c
Solution 1:
You can use the operator module to get functions equivalent to each of the operators.
importoperator
funcs = {
    '<': operator.lt,
    '<=': operator.le,
    '=': operator.eq,
    '>': operator.gt,
    '>=': operator.ge,
    '!=': operator.ne
}
def compute_mask(self, signal, comparator, value, df):
    return funcs[comparator](df[signal], value)
Solution 2:
I saw a neat solution like this recently where you list the cases as lamdbas in a dict, then you fetch the lamdba from the dict and call it in the return statement. In your case it would be something like this:
defcompute_mask(signal, comparator, value, df):
    cases = {
        '<': lambda df, signal, value: df[signal] < value
        '<=': lambda df, signal, value: df[signal] <= value
        '==': lambda df, signal, value: df[signal] == value
        '>=': lambda df, signal, value: df[signal] >= value
        '>': lambda df, signal, value: df[signal] > value
        '!=': lambda df, signal, value: df[signal] != value
    }
    return cases[comparator](df, signal, value)
Post a Comment for "Programmatically Picking An Inequality Operator"