【问题标题】:How to skip over errored lines in a for loop如何跳过for循环中的错误行
【发布时间】:2019-07-17 18:36:25
【问题描述】:

我正在进行 API 调用,但有时响应中没有某些字段。如果我遇到这些响应之一,我的脚本会按预期抛出 KeyError,但随后会完全跳出 for 循环。有没有办法让它简单地跳过错误的输出并继续循环?

我考虑过尝试将我正在搜索的所有字段放入一个列表中,并在遇到缺失字段时使用 continue 语句对其进行迭代,以保持迭代继续进行,但是 1) 看起来很麻烦 2)我在输出中有多个级别的迭代。

try:
    for item in result["results"]:
        print(MAJOR_SEP) # Just a line of characters separating the output
        print("NPI:", item['number'])
        print("First Name:", item['basic']['first_name'])
        print("Middle Name:", item['basic']['middle_name'])
        print("Last Name:", item['basic']['last_name'])
        print("Credential:", item['basic']['credential'])
    print(MINOR_SEP)
    print("ADDRESSES")
    for row in item['addresses']:
        print(MINOR_SEP)
        print(row['address_purpose'])
        print("Address (Line 1):", row['address_1'])
        print("Address (Line 2):", row['address_2'])
        print("City:", row['city'])
        print("State:", row['state'])
        print("ZIP:", row['postal_code'])
        print("")
        print("Phone:", row['telephone_number'])
        print("Fax:", row['fax_number'])

    print(MINOR_SEP)
    print("LICENSES")
    for row in item['taxonomies']:
        print(MINOR_SEP)
        print("State License: {} - {}, {}".format(row['state'],row['license'],row['desc']))

    print(MINOR_SEP)
    print("OTHER IDENTIFIERS")
    for row in item['identifiers']:
            print(MINOR_SEP)
            print("Other Identifier: {} - {}, {}".format(row['state'],row['identifier'],row['desc']))

    print(MAJOR_SEP)
except KeyError as e:
    print("{} is not defined.".format(e))

【问题讨论】:

  • try/except 放在每个循环中,而不是包装整个代码
  • 我想过,但这就像 25 个单独的 try-except 块。我希望有一个更好的方法,我只是没有考虑。
  • 这似乎很难帮助,因为这真的取决于我只能看到 3 fors
  • 所以,你说的是对每个部分使用 try-except 块,而不是每行输出。
  • 您可以编写一个单独的打印函数,并让该函数管理调用数据时发生的错误,或者类似的东西。

标签: python for-loop exception


【解决方案1】:

那些 try...except 块,特别是那些非常具体的错误,例如KeyError,应该只添加到重要的行周围。

如果您希望能够继续处理,至少将块放在 for 循环中,这样错误它将跳到迭代中的下一项。但更好的方法是验证这些值何时真正需要,并用一个虚拟值替换它们,以防它们不是。

例如:for row in item['addresses']:

可能是:for row in item.get('addresses', []):

因此,您将接受没有地址的物品

【讨论】:

  • 显然,我需要在文档中做更多的事情。 get() 方法非常适合访问字典中的项目而不会引发 KeyErrors。非常感谢!
【解决方案2】:

尝试在 for 之后使用 try/except 子句。

例如:

for item in result["results"]:
    try:
        # Code here.
    except KeyError as e:
        print("{} is not defined.".format(e))

Python 异常文档:https://docs.python.org/3/tutorial/errors.html

您也可以使用contextlib.suppress (https://docs.python.org/3/library/contextlib.html#contextlib.suppress)

例子:

from contextlib import suppress
for item in result["results"]:
    with suppress(KeyError):
        # Code here

【讨论】:

    猜你喜欢
    • 2013-01-22
    • 2012-12-13
    • 2015-08-20
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多