リストを反復処理しようとしていますが、反復がリストの最後に達したときにのみ特定の操作を実行する必要があります。以下の例を参照してください。
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")
どんな考えでも大歓迎です。