Have extra while loop conditions … based on a condition?

后端 未结 3 613
天涯浪人
天涯浪人 2021-01-03 01:05

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

3条回答
  •  借酒劲吻你
    2021-01-03 01:32

    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
    

提交回复
热议问题