使用比较语句作为函数中的参数,然后在 while 循环中作为条件传递



>想象一下我有一些这样的函数:

def func(condition):
while condition:
pass

有什么方法可以将比较作为条件传递,例如func(50 > x),但随后它不是按while False执行(x 将是低于 50 的值(,而是while 50 > x(我想做类似 x += 1 的事情,所以循环最终停止(? 我想这样做是因为我在两种不同的情况下将具有相同的函数,并且每种情况都有一个 while 循环,但条件必须彼此不同。到目前为止,我所做的是将另一个论点传递给func,所以def func(condition,situation),然后我会做while 50 > x if situation == 1 else True。但是,我相信我尝试这样做的方式会更快,因为按照我迄今为止的做法,在每次循环之后,不仅50 > xTrue必须再次评估,而且如果situation == 1

。这是关于我想做的

limit = 50
start = 0
def func(condition)
while condition:
pass
start += 1
# once I need the function like this, once I need it with True, so the loop runs forever in that case
func(limit > start)
func(True)

也许通过传递比较函数和所需的参数?像这样:

comparison_a = lambda x, y: x > y
comparison_b = lambda x, y: x <= y

(假设你的第二个条件是x <= y( 这将创建两个 lambda(用于简化(函数,这些函数与参数xy执行所需的比较

然后,您将函数创建为:

def func(comparison, start, limit):
while comparison(start, limit):
start += 1

并称其为:

limit = 50
start = 30
func(comparison_a, 50, 30)

或者,您可以使用operator模块,该模块将 python 运算符实现为函数。对于greater than运算符,您有operator.gt.举个例子:

import operator
limit = 50
start = 30
func(operator.gt, 50, 30)

虽然我建议不要使用这样的动态参数,但您可以使用内置的eval方法,该方法采用 Python 字符串并内联评估它。

def func(condition: String):
while eval(condition):
pass

最新更新