Programmatically picking an inequality operator

我的未来我决定 提交于 2021-02-11 12:22:33

问题


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 comparison string into a choice of inequality operator. Right now, this looks like

def compute_mask(self, signal, comparator, value, df):
    if comparator == '<':
        mask = df[signal] < value
    elif comparator == '<=':
        mask = df[signal] <= value
    elif comparator == '=':
        mask = df[signal] == value
    elif comparator == '>=':
        mask = df[signal] >= value
    elif comparator == '>':
        mask = df[signal] > value
    elif comparator == '!=':
        mask = df[signal] != value
    
    return mask

In other applications, I was able to do something like

func = {
    'a': func_a,
    'b': func_b,
    'c': func_c
}.get(func_choice)
func(value_to_process)

in order to easily avoid having to repeat code over and over. How would I go about doing the same thing here?


回答1:


You can use the operator module to get functions equivalent to each of the operators.

import operator

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)



回答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:

def compute_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)


来源:https://stackoverflow.com/questions/66125362/programmatically-picking-an-inequality-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!