我需要在Python程序中模拟一个do-while循环。不幸的是,下面的简单代码不能工作:

list_of_ints = [ 1, 2, 3 ]
iterator = list_of_ints.__iter__()
element = None

while True:
  if element:
    print element

  try:
    element = iterator.next()
  except StopIteration:
    break

print "done"

不是"1,2,3,done",而是输出如下:

[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', '  File "test_python.py", line 8, in <module>
    s = i.next()
', 'StopIteration
']

为了捕获“停止迭代”异常并中断一段时间,我能做些什么 循环正常吗?

下面的伪代码显示了为什么需要这样一个东西的示例。

状态机:

s = ""
while True :
  if state is STATE_CODE :
    if "//" in s :
      tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
      state = STATE_COMMENT
    else :
      tokens.add( TOKEN_CODE, s )
  if state is STATE_COMMENT :
    if "//" in s :
      tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
    else
      state = STATE_CODE
      # Re-evaluate same line
      continue
  try :
    s = i.next()
  except StopIteration :
    break

当前回答

下面的代码可能是一个有用的实现,突出了do-while和while之间的主要区别。

在这种情况下,你总是至少要循环一次。

first_pass = True
while first_pass or condition:
    first_pass = False
    do_stuff()

其他回答

do {
  stuff()
} while (condition())

->

while True:
  stuff()
  if not condition():
    break

你可以做一个函数:

def do_while(stuff, condition):
  while condition(stuff()):
    pass

但 1)它很丑。 2) Condition应该是一个只有一个参数的函数,应该由东西填充(这是不使用经典while循环的唯一原因)。

内置的iter函数具体做到了这一点:

for x in iter(YOUR_FN, TERM_VAL):
    ...

例如(在Py2和3中测试过):

class Easy:
  X = 0
  @classmethod
  def com(cls):
    cls.X += 1
    return cls.X

for x in iter(Easy.com, 10):
  print(">>>", x)

如果你想给出一个终止条件而不是一个值,你总是可以设置一个等式,并要求这个等式为True。

快速攻击:

def dowhile(func = None, condition = None):
    if not func or not condition:
        return
    else:
        func()
        while condition():
            func()

像这样使用:

>>> x = 10
>>> def f():
...     global x
...     x = x - 1
>>> def c():
        global x
        return x > 0
>>> dowhile(f, c)
>>> print x
0
while condition is True: 
  stuff()
else:
  stuff()

我相信python上的这个do-while模拟的语法格式与C和Java中呈现的do-while结构格式最接近。

do = True
while do:
    [...]
    do = <condition>