最简单的写作方式“而不是初始值”

问题描述 投票:0回答:3

如果你想在变量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)
python python-3.x logic cycle
3个回答
1
投票

如果你正在寻找一个repeat-until结构,那么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)

3
投票

如果条件在主体末尾为真,则使用显式中断的无限循环。

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

0
投票

另一种干净的方法是在循环之前评估一次语句。

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生成一次,然后进入循环。

© www.soinside.com 2019 - 2024. All rights reserved.