我试图通过列表迭代,我需要执行特定操作时,当迭代达到列表的末尾,只有,见下面的例子:迭代通过列表和处理的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")
任何想法都欢迎。
用'else'替换'finally'? – WolframH 2012-07-05 20:29:44
为什么你有''所有项目都不成功''而不是''所有项目都不成功'''?如果它运行,那么中间的撇号将会破坏你的字符串/异常。另外,对于WolframH的观点,请参阅[docs](http://docs.python.org/reference/compound_stmts.html#for) - 'else'而不是'finally'应该可以工作。 – thegrinner 2012-07-05 20:31:33
值得注意的是,'except:'是一件可怕的事情 - 如果仅仅是例子,那么很好,但在任何实际的例子中,请只捕捉一个特定的例外。 – 2012-07-05 20:34:14