python - 有没有办法让条件语句成为我可以传递给 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
编码True
or False
,而不是可能会改变每次迭代的实际条件语句。
解决方案
这不起作用,因为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 - 如何在 gvim 的新命令行窗口中运行 python 文件
- firebase - Flutter 错误:引发了另一个异常:'DiagnosticsProperty 的实例
' . 重定向到该页面时显示空白屏幕 - vue.js - 具有获取请求值的 Vue 路由参数
- python - 如何在搁置中设置价值
- php - PHP 全局迭代功能
- intellij-idea - Jetbrains Intellij 格式化代码样式问题
- c# - 使用 NSIS 安装程序安装的应用程序无法启动
- etl - 数据仓库建模
- javascript - 如何检测嵌套 div (React) 中的溢出?
- javascript - 猫鼬:如何按日期查找以给定输入开头的日期(如自动完成:25/01/2...,25/01..)