Have extra while loop conditions … based on a condition?

时光怂恿深爱的人放手 提交于 2019-11-29 20:04:27

问题


The variable a can take any number of values. The value of a is the amount of extra pre-defined conditions to have for the while loop.

This can be done with multiple elif statements but is there a cleaner way of doing this?

if a == 0:
    while condition_1:
        ...
elif a == 1:
    while condition_1 or condition_2:
        ...
elif a == 2:
    while condition_1 or condition_2 or condition_3:
        ...

回答1:


A general way of doing what other languages do with a switch statement is to create a dictionary containing a function for each of your cases:

conds = {
    0: lambda: condition_1,
    1: lambda: condition_1 or condition_2,
    2: lambda: condition_1 or condition_2 or condition_3
}

Then:

while conds[a]():
    # do stuff

By using lambdas (or named functions if your conditions are particularly complex) the appropriate condition can be evaluated each time through the loop, instead of once when the dictionary is defined.

In this simple case where your a has sequential integer values starting at 0, you could use a list and save a bit of typing. To further simplify, you could define each of your conditions in terms of the previous one, since you're just adding a condition each time:

conds = [
     lambda: condition_1,
     lambda: conds[0]() or condition_2,
     lambda: conds[1]() or condition_3
]

Or, as suggested by Julien in a comment:

conds = [
     lambda: condition_1,
     lambda: condition_2,
     lambda: condition_3
]

while any(cond() for cond in conds[:a+1]):
    # do stuff



回答2:


Have you tried something like this:

while (a >= 0 and condition_1) or (a >= 1 and condition_2) or (a >= 2 and condition_3) ...



回答3:


You could define a function to be evaluated for while:

def test(a):
    if a == 1:
        return condition1(...)
    elif a == 2:
        return condition2(...) or condition1(...)
    elif a == 3:
        return condition2(...) or condition1(...) or condition3(...)
    else:
        return False

# test(a) will check the conditions ... define additional arguments if you need them
while test(a):
    do_stuff

It does have still the elifs but you don't need to write the while-loop multiple times.



来源:https://stackoverflow.com/questions/36025026/have-extra-while-loop-conditions-based-on-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!