首页 > 解决方案 > 有没有办法让条件语句成为我可以传递给 Python 循环的变量?

问题描述

我想做类似的事情:

def myfunc(p1, p2, p3):
   time_step = 0
   if p1 <= 0
      while (p2 > 0 or p3 > 0)
         stuff that updates p2, p3
         timestep+=1
   else
      while (time_step < p1)
         stuff that updates p2, p3
         timestep+=1

基本上,我希望能够让用户决定他们是否希望 while 循环运行直到 p2 和 p3 小于或等于 0,或者他们是否希望 while 循环运行直到所需的 time_step。在任何一种情况下,“更新 p2、p3 的东西”都是完全相同的。但是,while 循环中的内容由很多行组成,我只是复制和粘贴“更新 p2、p3 的内容”。我觉得必须有更好的方法。

我希望以下内容会起作用:

def myfunc(p1, p2, p3):
   time_step = 0
   if p1 <= 0
      conditional_statement = (p2 > 0 or p3 > 0)
   else
      conditional_statement = (time_step < p1)
   
   while (conditional_statement)
      stuff that updates p2, p3
      timestep+=1

但是,我遇到了一个无限循环,因为conditional_statement编码Trueor False,而不是可能会改变每次迭代的实际条件语句。

标签: pythonwhile-loopconditional-statements

解决方案


这不起作用,因为conditional_statement它是一个布尔变量,并且只会在while循环开始之前计算一次。您可以做的是将其转换为返回布尔值的函数(为简洁起见,也可以是 lambda 函数):

if p1 <= 0:
    conditional_statement = lambda: (p2 > 0 or p3 > 0)
else:
    conditional_statement = lambda: (time_step < p1)

然后你应该调用()你刚刚创建的函数对象(通过附加):

while conditional_statement():
    # Do things

推荐阅读