【问题标题】:Have extra while loop conditions ... based on a condition?有额外的while循环条件......基于条件?
【发布时间】:2016-03-16 01:00:32
【问题描述】:

变量a 可以采用任意数量的值。 a 的值是 while 循环所具有的额外预定义条件的数量。

这可以通过多个 elif 语句来完成,但是有没有更简洁的方法呢?

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:
        ...

【问题讨论】:

  • 你想完成什么?请给我们一个更具体的例子吗?

标签: python while-loop


【解决方案1】:

其他语言对switch 语句所做的一般方法是为每个案例创建一个包含函数的字典:

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

然后:

while conds[a]():
    # do stuff

通过使用 lambdas(或命名函数,如果您的条件特别复杂),可以在每次循环中计算适当的条件,而不是在定义字典时计算一次。

在这个简单的情况下,您的a 具有从 0 开始的连续整数值,您可以使用列表并节省一些输入。为了进一步简化,您可以根据前一个条件定义每个条件,因为您每次只是添加一个条件:

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

或者,正如 Julien 在评论中所建议的那样:

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

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

【讨论】:

  • +1 关于一个聪明而简单的解决方案。但是,您可能想说明为什么 lambdas - 如果我解释正确,那是因为不使用它们会导致布尔值在字典初始化时被固定,对吗?
  • 是的。您还可以将命名函数用于特别复杂的条件。在任何情况下,它都需要一个函数来推迟评估(并允许重复评估)。
  • 我个人建议直接将其放入答案中,所以如果有不懂的人进来,他们会立即得到解释
  • 小改进(也许?):定义conds = [lambda: cond1, lambda: cond2, ...],然后定义while any([cond() for cond in conds[:a]])
  • 括号是必需的,因为conds[a] 是一个函数,必须调用它才能评估其中定义的条件。有点令人困惑的是,函数对象本身就是“真实的”,所以如果你不调用函数,你的 while 循环就会永远运行。
【解决方案2】:

你有没有尝试过这样的事情:

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

【讨论】:

  • 虽然在技术上是正确的,但我想提醒读者,这是一个有点冗长、过度且非 Pythonic 的解决方案,尤其是在条件变得越来越复杂的情况下。
  • 虽然不那么优雅,但您的回答对我来说马上就奏效了。你能帮我解释一下,它是如何工作的吗? (a >= 0 and condition_1) 是 mini-if 语句吗?
  • and 关键字在逻辑上等同于嵌套的if 语句,所以,排序...
【解决方案3】:

你可以定义一个函数来评估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

它仍然有 elif,但您不需要多次编写 while-loop。

【讨论】:

    猜你喜欢
    • 2020-11-03
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2019-08-26
    • 2016-03-30
    相关资源
    最近更新 更多