如何将运算符传递给 python 函数? [英] How to pass an operator to a python function?
本文介绍了如何将运算符传递给 python 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将数学运算符以及要比较的数值传递给函数.这是我损坏的代码:
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
并调用它
get_truth(1.0,'>',0.0)
应该返回 True.
推荐答案
看看 运营商模块:
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
这篇关于如何将运算符传递给 python 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文