我正在解析一个JSON数据流的代码中。对于每个数组,我有以下代码:
for node in parse_me:
# It's important that one iteration failing doesn't cause all iterations to fail.
try:
i = node['id'] # KeyError?
function_that_needs_int (i) # TypeError?
# possibly other stuff
except Exception as e:
LogErrorMessage ('blah blah blah {} in node {}'.fmt(e, node))
我不喜欢这会让我的for循环嵌套两层,仅仅是因为我需要防止异常中断循环。有没有一种方法可以使这段代码更加扁平化?