如何将操作符传递给python函数?

phi*_*hem 38 python function python-2.7

我想将一个数学运算符和要比较的数值传递给一个函数.这是我破碎的代码:

def get_truth(inp,relate,cut):    
    if inp print(relate) cut:
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

并称之为

get_truth(1.0,'>',0.0)
Run Code Online (Sandbox Code Playgroud)

哪个应该返回True.

grc*_*grc 56

看看运营商模块:

import operator
get_truth(1.0, operator.gt, 0.0)

...

def get_truth(inp, relate, cut):    
    return relate(inp, cut)
    # you don't actually need an if statement here
Run Code Online (Sandbox Code Playgroud)

  • 我希望能够动态更改运算符(因此我可能不得不回到函数解决方案)。 (2认同)

ale*_*cxe 35

制作字符串和操作符函数的映射.此外,您不需要if/else条件:

import operator


def get_truth(inp, relate, cut):
    ops = {'>': operator.gt,
           '<': operator.lt,
           '>=': operator.ge,
           '<=': operator.le,
           '=': operator.eq}
    return ops[relate](inp, cut)


print get_truth(1.0, '>', 0.0)  # prints True
print get_truth(1.0, '<', 0.0)  # prints False
print get_truth(1.0, '>=', 0.0)  # prints True
print get_truth(1.0, '<=', 0.0)  # prints False
print get_truth(1.0, '=', 0.0)  # prints False
Run Code Online (Sandbox Code Playgroud)

仅供参考,eval()是邪恶的:在Python中使用eval是一种不好的做法吗?

  • +1.此外,这个答案表明你可以直接返回`ops [associated]`的值,而不是显式测试它并返回一个文字`True`或'False`. (3认同)

Vik*_*kez 12

使用该operator模块.它包含您可以在python中使用的所有标准运算符.然后使用运算符作为函数:

import operator

def get_truth(inp, op, cut):
    return op(inp, cut):

get_truth(1.0, operator.gt, 0.0)
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用字符串作为运算符,那么创建一个从字符串到运算符函数的字典映射,如@alecxe建议的那样.