2012-07-05 4 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") 

私はこのコードがあまりPythonではないと思うので、私はより良い方法を探しています。私は理想的なコードは以下のこの架空の作品のようになるはずだと思う:

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

「finally」を「else」に置き換えますか? – WolframH

+0

なぜ「すべてのアイテムが成功しなかった」の代わりに「すべてのアイテムが成功していません」と表示されていますか?その中間アポストロフィが実行されると、あなたの文字列/例外が破られます。また、WolframHのポイントには、[docs](http://docs.python.org/reference/compound_stmts.html#for)を参照してください。 - 「finally」ではなく「else」が機能するはずです。 – thegrinner

+1

'except:'は恐ろしいことですが、これは単なる例ですが、実際の例では特定の例外を捕捉してください。 –

答えて

16

あなたはforループの後elseを使用することができますし、あなたがforループのうちbreakしなかった場合はその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ステートメントはを実行せずにループを終了210節のスイート。

+1

私はそれを入力していた。 +1 - これが最良の方法です。 –

+0

はい、それは明らかでした、ありがとう! –

関連する問題