Ser*_*ski 8 python iterator list stopiteration
我正在尝试遍历列表,我需要在迭代到达列表末尾时执行特定操作,请参阅下面的示例:
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")
Run Code Online (Sandbox Code Playgroud)
我相信这段代码不是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")
Run Code Online (Sandbox Code Playgroud)
欢迎任何想法.
And*_*ark 17
您可以else在for循环之后使用,并且else只有在您没有break退出for循环时才执行其中的代码:
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")
Run Code Online (Sandbox Code Playgroud)
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
Run Code Online (Sandbox Code Playgroud)
一个
break在首套房执行的语句终止循环,不执行该else条款的套件.
| 归档时间: |
|
| 查看次数: |
8812 次 |
| 最近记录: |