有没有办法让条件语句成为我可以传递给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编码TrueFalse,而不是可能会改变每次迭代的实际条件语句。

回答

这将不起作用,因为它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


以上是有没有办法让条件语句成为我可以传递给Python循环的变量?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>