8

リストを反復処理しようとしていますが、反復がリストの最後に達したときにのみ特定の操作を実行する必要があります。以下の例を参照してください。

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")

どんな考えでも大歓迎です。

4

1 に答える 1

18

forループの後に使用できelse、その中のコードは、forループから出elseていない場合にのみ実行さbreakれます。

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")

これは、ステートメントのドキュメント、for以下に示す関連部分で見つけることができます。

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

最初のスイートで実行されたステートメントは、句のスイートbreakを実行せずにループを終了します。else

于 2012-07-05T20:30:19.573 に答える