是否可以将比较运算符作为参数传递到函数中



有没有办法在函数的参数中指定if条件中的函数?例如,我希望能够做这样的事情:

a = int(input('number between 0 and 5'))
b = >=
def fun1(a, b):
if a b 0:
print('...')

是的,如果您想使用比较运算符作为函数的参数,可以使用operator库中的方法——在这种情况下,您正在寻找operator.ge:

import operator
a = int(input('number between 0 and 5'))
b = operator.ge
def fun1(a, b):
if b(a, 0):
print('...')

BrokenBenchmark是对的,传递函数是实现这一点的方法。我想解释一下幕后发生的事情。

由于这是将函数作为参数传递(附带说明:这意味着python函数是一流的函数(,因此有两种方法可以实现这一点:传递函数或lambda(内联函数(。以下是两者的两个例子。

def b_func(x, y):
return x >= y
b_lambda = lambda x, y: x >= y
a = int(input('number between 0 and 5'))
def fun1(a, b):
if b(a, 0):
print('...')

fun1(a, b_func)
fun1(a, b_lambda)

最新更新