如何将运算符传递给 python 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18591778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass an operator to a python function?
提问by philshem
I'd like to pass a math operator, along with the numeric values to compare, to a function. Here is my broken code:
我想将数学运算符以及要比较的数值传递给函数。这是我损坏的代码:
def get_truth(inp,relate,cut):
if inp print(relate) cut:
return True
else:
return False
and call it with
并调用它
get_truth(1.0,'>',0.0)
which should return True.
这应该返回True。
采纳答案by grc
Have a look at the operator module:
看看操作员模块:
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
回答by Viktor Kerkez
Use the operator
module. It contains all the standard operators that you can use in python. Then use the operator as a functions:
使用operator
模块。它包含您可以在 python 中使用的所有标准运算符。然后将运算符用作函数:
import operator
def get_truth(inp, op, cut):
return op(inp, cut):
get_truth(1.0, operator.gt, 0.0)
If you really want to use strings as operators, then create a dictionary mapping from string to operator function as @alecxe suggested.
如果您真的想使用字符串作为运算符,那么按照@alecxe 的建议创建一个从字符串到运算符函数的字典映射。
回答by Paul Evans
Use the operator
module instead:
改用operator
模块:
import operator
def get_truth(inp, relate, cut):
rel_ops = {
'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
'==': operator.eq,
'!=': operator.ne
}
return rel_ops[relate](inp, cut)
回答by alecxe
Make a mapping of strings and operatorfunctions. Also, you don't need if/else condition:
制作字符串和运算符函数的映射。此外,您不需要 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
FYI, eval()
is evil: Is using eval in Python a bad practice?
仅供参考,eval()
是邪恶的:在 Python 中使用 eval 是一种不好的做法吗?
回答by amadain
>>> 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
>>>