python - 遍历列表并在 Python 中漂亮地处理 StopIteration

标签 python list iterator 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")

我相信这段代码不太像 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")

欢迎任何想法。

最佳答案

您可以在 for 循环之后使用 else,并且 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")

您可以在 documentation for the for statement 中找到它, 相关部分如下所示:

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

A break statement executed in the first suite terminates the loop without executing the elseclause’s suite.

关于python - 遍历列表并在 Python 中漂亮地处理 StopIteration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11352099/

相关文章:

python - 限制py-redis中redis的连接数

python - 仅返回使用 PyGithub 的问题

html - CSS 四列宽度

list - 删除列表中的重复项(Prolog)

c++ - 我可以/应该从 STL 迭代器继承吗?

python - Django 发送电子邮件困惑

python -/usr/bin/clang 命令在 MacOS 上尝试 pip 安装 TA-lib 失败

c# - 比较两个列表

java - enhanced-for循环增强到什么程度呢?

javascript - javascript中异步生成器的目的是什么?