在Python中模拟一个并发循环?我需要模拟Python程序中的并发循环。不幸的是,以下简单的代码不起作用:list_of_ints = [ 1, 2, 3 ]iterator = list_of_ints.__iter__()element = Nonewhile True:
if element:
print element try:
element = iterator.next()
except StopIteration:
breakprint "done"它没有打印“1,2,3,Done”,而是打印以下输出:[stdout:]1[stdout:]2[stdout:]3None['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
5 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
while True: stuff() if fail_condition: break
stuff()while not fail_condition: stuff()
for i in l: print iprint "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
精慕HU
TA贡献1845条经验 获得超8个赞
condition = Truewhile condition: # loop body here condition = test_loop_condition()# end of loop
添加回答
举报
0/150
提交
取消