我需要在Python程序中模拟do-while循环。不幸的是,以下简单的代码不起作用:
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 ']
为了捕获“停止迭代”异常并正确中断while循环,我该怎么办?
为什么需要这种东西的一个示例在下面显示为伪代码。
状态机:
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 True: stuff() if fail_condition: break
要么:
stuff() while not fail_condition: stuff()
你在尝试使用do while循环来打印列表中的内容在做什么?为什么不使用:
for i in l: print i print "done"
更新:
那你有行列表吗?而你想继续迭代呢?怎么样:
for s in l: while True: stuff() # use a "break" instead of s = i.next()
看起来像你想要的东西吗?在你的代码示例中,它将是:
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