2012-07-05 25 views
8

我试图通过列表迭代,我需要执行特定操作时,当迭代达到列表的末尾,只有,见下面的例子:迭代通过列表和处理的StopIteration在Python精美

data = [1, 2, 3] 

data_iter = data.__iter__() 
try: 
    while True: 
     item = data_iter.next() 
     try: 
      do_stuff(item) 
      break # we just need to do stuff with the first successful item 
     except: 
      handle_errors(item) # in case of no success, handle and skip to next item 
except StopIteration: 
    raise Exception("All items weren't successful") 

我相信这段代码不是太Pythonic,所以我正在寻找更好的方法。我认为理想的代码应该看起来像下面的这个假设片:

data = [1, 2, 3] 

for item in data: 
    try: 
     do_stuff(item) 
     break # we just need to do stuff with the first successful item 
    except: 
     handle_errors(item) # in case of no success, handle and skip to next item 
finally: 
    raise Exception("All items weren't successful") 

任何想法都欢迎。

+0

用'else'替换'finally'? – WolframH 2012-07-05 20:29:44

+0

为什么你有''所有项目都不成功''而不是''所有项目都不成功'''?如果它运行,那么中间的撇号将会破坏你的字符串/异常。另外,对于WolframH的观点,请参阅[docs](http://docs.python.org/reference/compound_stmts.html#for) - 'else'而不是'finally'应该可以工作。 – thegrinner 2012-07-05 20:31:33

+1

值得注意的是,'except:'是一件可怕的事情 - 如果仅仅是例子,那么很好,但在任何实际的例子中,请只捕捉一个特定的例外。 – 2012-07-05 20:34:14

回答

16

您可以后使用else for循环,如果你没有break出来的for循环时,才会执行该else内的代码:

data = [1, 2, 3] 

for item in data: 
    try: 
     do_stuff(item) 
     break # we just need to do stuff with the first successful item 
    except Exception: 
     handle_errors(item) # in case of no success, handle and skip to next item 
else: 
    raise Exception("All items weren't successful") 

您可以在documentation for the for statement,相关作品找到这个如下图所示:

for_stmt ::= "for" target_list "in" expression_list ":" suite 
       ["else" ":" suite] 

在第一套件执行的break语句终止循环,而不执行else条款的套件。

+1

正如我打字一样。 +1 - 这是做这件事的最好方式。 – 2012-07-05 20:33:29

+0

是的,很明显,谢谢! – 2012-07-05 20:34:00