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

您可以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")

您可以在声明的文档中for找到它,相关部分如下所示:

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

在第一个套件中执行的break语句终止循环而不执行该else子句的套件。

于 2012-07-05T20:30:19.573 回答