gpt4 book ai didi

python - 如何将运算符传递给python函数?

转载 作者:IT老高 更新时间:2023-10-28 21:48:25 25 4
gpt4 key购买 nike

我想将一个数学运算符以及要比较的数值传递给一个函数。这是我损坏的代码:

def get_truth(inp,relate,cut):    
if inp print(relate) cut:
return True
else:
return False

并调用它

get_truth(1.0,'>',0.0)

应该返回 True。

最佳答案

看看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

关于python - 如何将运算符传递给python函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18591778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com