【问题标题】:Iterate through list and handle StopIteration in Python beautifully遍历列表并在 Python 中精美地处理 StopIteration
【发布时间】:2012-07-06 07:35:13
【问题描述】:

我正在尝试遍历一个列表,当且仅当迭代到达列表末尾时,我需要执行特定操作,请参见下面的示例:

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

欢迎提出任何想法。

【问题讨论】:

  • 用else替换finally?
  • 为什么你有'All items weren't successful'而不是"All items weren't successful"?如果它运行,中间的撇号会破坏你的字符串/异常。此外,就 WolframH 而言,请参阅 docs - else 而不是 finally 应该可以工作。
  • 值得注意的是,except: 是一个可怕的东西——如果只是举例,那很好,但在任何真实的例子中,请只捕获一个特定的异常。
  • 是的...至少except Exception。
  • @WolframH 谢谢,已经知道了

标签: python list iterator stopiteration


【解决方案1】:

您可以在 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]

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

【讨论】:

  • 当我在打字的时候。 +1 - 这是最好的方法。
猜你喜欢
  • 2023-01-14
  • 2016-03-06
  • 2021-12-13
  • 2018-01-09
  • 2013-02-18
  • 1970-01-01
  • 2018-03-08
  • 2015-10-07
相关资源
最近更新 更多