Python 将带有值的比较运算符传递给函数

Python 将带有值的比较运算符传递给函数,python,function,arguments,operators,comparison-operators,Python,Function,Arguments,Operators,Comparison Operators,我正在定义一个函数,其中一个参数应该是比较运算符 我尝试过不同版本的转换命令,比如float和input 我正在尝试的代码: def factor_test(factor1, factor2, criteria1, text, criteria2): bool_mask1 = rnt2[factor1].str.contains(criteria1,na=False) bool_mask2 = rnt2[factor2] criteria2 # Returns value

我正在定义一个函数,其中一个参数应该是比较运算符

我尝试过不同版本的转换命令,比如float和input

我正在尝试的代码:

def factor_test(factor1, factor2, criteria1, text, criteria2):
    bool_mask1 = rnt2[factor1].str.contains(criteria1,na=False)
    bool_mask2 = rnt2[factor2] criteria2
    # Returns values that are TRUE i.e. an error, not an Boolean dataframe but actual values
    test_name = rnt2[(bool_mask1) & (bool_mask2)] 
标准2
应为
>0.75

bool_mask2 = rnt2[factor2] > 0.75

最好是一个参数,我可以在其中输入
0.75
,该函数应该使用大约15次,使用
=
==
使用
操作员
模块:

def factor_test(factor1, factor2, criteria1, text, criteria2, op):
    bool_mask1 = rnt2[factor1].str.contains(criteria1,na=False)
    bool_mask2 = op(rnt2[factor2], criteria2)
    test_name = rnt2[(bool_mask1) & (bool_mask2)] 
然后与不同的接线员通话:

import operator

factor_test(factor1, factor2, criteria1, text, criteria2, operator.le)  # <=
factor_test(factor1, factor2, criteria1, text, criteria2, operator.eq)  # ==
# etc
导入操作符

factor_test(factor1、factor2、criteria1、text、criteria2、operator.le)#如果要将比较运算符及其值作为一个参数传递,则有几个选项:

  • 使用函数和:

    import operator
    from functools import partial
    
    # simple example function
    def my_function(condition):
        return condition(1)
    
    two_greater_than = partial(operator.gt, 2)
    my_function(two_greater_than)
    # True
    
    two_greater_than = (2).__gt__
    my_function(two_greater_than)
    # True
    
    def two_greater_than(x):
        return 2 > x
    
    my_function(two_greater_than)
    # True
    
  • 使用:

    import operator
    from functools import partial
    
    # simple example function
    def my_function(condition):
        return condition(1)
    
    two_greater_than = partial(operator.gt, 2)
    my_function(two_greater_than)
    # True
    
    two_greater_than = (2).__gt__
    my_function(two_greater_than)
    # True
    
    def two_greater_than(x):
        return 2 > x
    
    my_function(two_greater_than)
    # True
    
  • 使用
    lambda
    (如中所示)

  • 使用函数:

    import operator
    from functools import partial
    
    # simple example function
    def my_function(condition):
        return condition(1)
    
    two_greater_than = partial(operator.gt, 2)
    my_function(two_greater_than)
    # True
    
    two_greater_than = (2).__gt__
    my_function(two_greater_than)
    # True
    
    def two_greater_than(x):
        return 2 > x
    
    my_function(two_greater_than)
    # True
    

  • 将这些方法中的任何一种应用于具有多个参数的函数都应该是微不足道的。

    lambda x:x>0.75
    ?非常相关但不完全重复: