How to pass an operator to a python function?
我想给一个函数传递一个数学运算符和要比较的数值。这是我的密码:
1 2 3 4 5 | def get_truth(inp,relate,cut): if inp print(relate) cut: return True else: return False |
然后打电话给
1 | get_truth(1.0,'>',0.0) |
号
这应该是真的。
有一个模块:look at the operatorP></
1 2 3 4 5 6 7 8 | 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 |
of strings和社会的映射函数。你不也,if / else condition:needP></
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
fyi
茶
1 2 3 4 5 6 | import operator def get_truth(inp, op, cut): return op(inp, cut): get_truth(1.0, operator.gt, 0.0) |
如果你真的想使用字符串作为经营者,然后创建的映射函数从字符串字典alecxe suggested as to社"。P></
1 2 3 4 5 6 7 8 9 | >>> def get_truth(inp,relate,cut): ... if eval("%s%s%s" % (inp,relate,cut)): ... return True ... else: ... return False ... >>> get_truth(1.0,'>',0.0) True >>> |
你想使用
1 | if eval(str(inp) + relate + str(cut)):` |