最简单的写法"while not the initial value"

Simplest way of writing "while not the initial value"

如果您想在变量 foo != 5 时执行某些操作,初始值为 5(例如)。

有谁知道更简洁的方法吗? 一种方式是:

def try1():
    foo = 5
    aux = False
    while (foo != 5) or (aux == False):
        aux = True
        foo = (random.randint(1,100) // (foo +1)) +1
        print(foo)

如果主体的 end 条件为真,则使用明确中断的无限循环。

def try1():
    foo = 5
    while True:
        foo = (random.randint(1,100) // (foo +1)) +1
        print(foo)
        if foo == 5:
            break

如果您要查找重复直到结构,Python 中没有。但是,您可以通过创建迭代器来获得类似的东西。然后,您可以在 for _ in ... 语句中使用该迭代器以获得所需的行为。

  def repeatUntil(condition):
      yield
      while not condition(): yield

  foo = 5
  for _ in repeatUntil(lambda:foo==5):
     foo = (random.randint(1,100) // (foo +1)) +1
     print(foo)

如果你想表达继续条件而不是停止条件,或者repeatWhile()。 (在这两种情况下,条件将在循环结束时进行测试)

  def repeatWhile(condition):
      yield
      while condition(): yield

  foo = 5
  for _ in repeatWhile(lambda:foo!=5):
     foo = (random.randint(1,100) // (foo +1)) +1
     print(foo)

请注意,此方法将提供 continue 的正确处理,而 while True: ... if foo==5: break 则需要额外的代码(和额外的注意)。

例如:

foo = 5
while True:
    foo = (random.randint(1,100) // (foo +1)) +1
    if someCondition == True: continue # loop will not stop even if foo == 5
    print(foo)
    if foo == 5: break

[更新] 如果您更喜欢使用 while 语句并且不希望有 lambda: 的方式,您可以创建一个 loopUntilTrue()管理强制第一遍的函数:

def loopUntilTrue():  # used in while not loop(...):
    firstTime = [True]
    def loop(condition):
        return (not firstTime or firstTime.clear()) and condition
    return loop

foo = 5
reached = loopUntilTrue()
while not reached(foo==5):    
    foo = (random.randint(1,100) // (foo +1)) +1
    print(foo)

请注意,您需要为每个 while 语句初始化一个 loopUntilTrue() 的新实例。这也意味着您必须在使用这种方法的嵌套 while 循环中使用不同的变量名称(对于 reached

你可以用退出条件做同样的事情:

def loopUntilFalse(): # used in while loop(...):
    firstTime = [True]
    def loop(condition):
        return (firstTime and not firstTime.clear()) or condition
    return loop

foo = 5
outcome = loopUntilFalse()
while outcome(foo!=5):    
    foo = (random.randint(1,100) // (foo +1)) +1
    print(foo)

另一种简洁的方法是在循环之前对语句求值一次。

def try1():
    foo = 5

    foo = (random.randint(1,100) // (foo +1)) +1
    print(foo)

    while foo != 5:
        foo = (random.randint(1,100) // (foo +1)) +1
        print(foo)

这样就生成了一次foo,然后进入循环