如何将运算符传递给python函数? [英] How to pass an operator to a python function?

查看:134
本文介绍了如何将运算符传递给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

和使用

and call it with

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆