如何模拟 do-while 循环? [英] How to emulate a do-while loop?
问题描述
我需要在 Python 程序中模拟 do-while 循环.不幸的是,以下简单的代码不起作用:
I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
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",而是以下输出:
Instead of "1,2,3,done", it prints the following output:
[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', ' File "test_python.py", line 8, in <module>
s = i.next()
', 'StopIteration
']
我该怎么做才能捕获停止迭代"异常并暂停一段时间正确循环?
What can I do in order to catch the 'stop iteration' exception and break a while loop properly?
为什么可能需要这样的东西的示例如下所示为伪代码.
An example of why such a thing may be needed is shown below as pseudocode.
状态机:
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 循环:
I am not sure what you are trying to do. You can implement a do-while loop like this:
while True:
stuff()
if fail_condition:
break
或者:
stuff()
while not fail_condition:
stuff()
你在做什么尝试使用 do while 循环打印列表中的内容?为什么不直接使用:
What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:
for i in l:
print i
print "done"
更新:
所以你有行列表吗?你想继续迭代它吗?怎么样:
So do you have a list of lines? And you want to keep iterating through it? How about:
for s in l:
while True:
stuff()
# use a "break" instead of s = i.next()
这看起来与您想要的很接近吗?使用您的代码示例,它将是:
Does that seem like something close to what you would want? With your code example, it would be:
for s in some_list:
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] )
break # get next s
else:
state = STATE_CODE
# re-evaluate same line
# continues automatically
这篇关于如何模拟 do-while 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!