Python:While 循环,在不同条件下执行相同的代码。优雅与架空

标签 python while-loop

在 python 中: 我希望在 while 循环中执行相同的代码块,但在不同的条件下,带有一个应该检查哪个条件的标志。 此外,在这种情况下,标志不会在执行期间更改,并且只有一个标志对于程序的这一部分是事件的。

我可以这样做:

#user inputs flag
if flag == "flag1": flag1 = True
elif flag == "flag2": flag2 = True
#...
#define parameters    
while (flag1 and condition1) or (flag2 and condition2) ... or (flagN and conditionN):
    #do stuff #using parameters

由于“and”在 python 中的工作方式,这种方法可以,因为它只会检查标志,而不会每次都计算每个括号的条件。

def dostuff(parameters):
    #do stuff

#user inputs flag
if flag == "flag1": flag1 = True
elif flag == "flag2": flag2 = True
#...

#define parameters

if flag1:
    while(condition1):
        dostuff(parameters)
elif flag2:
    while(condition2):
        dostuff(parameters)
etc... down to N

会完成相同的事情,可能是相同的开销。

我只是想知道是否有人可以在编程实践和可读性方面提出更好的方法,或者这是否是最好的通用方法。

谢谢

最佳答案

您可以使用 lambda 表达式的 dict:

conditions = {
    flag1: lambda: cond1,
    flag2: lambda: cond2,
    flag3: lambda: cond3}

while conditions[flag]():
    do_stuff(parameters)

例子:

conditions = {
    "flag1": lambda: x < 10,
    "flag2": lambda: x < 3,
    "flag3": lambda: x < 5}

x = 0
while conditions["flag2"]():
    print(x)
    x += 1

输出:

0
1
2

关于Python:While 循环,在不同条件下执行相同的代码。优雅与架空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30053128/

相关文章:

c - 文件 I/O 问题 - 冲突的 while 循环

python - 文本位置未显示在绘图上

python - 如何将 python Socket.IO 与 Qt 集成

python - 为什么 i += 1 更改为 i += 2 有效?

java - 当用户输入 null 时如何退出循环

javascript - 在哪些情况下我应该使用 'while loops' 而不是 JavaScript 中的“for 循环”?

python - 为 MVC 模式组织我的 python 项目,

python - 如何在 Pandas 中绘制和标记多个自相关函数?

python - 在垂直条 matplotlib 和 python 中绘制像素

java - 为什么这个 while 循环在 roll and roll 2 之后不停止?