【问题标题】:How to report and fix errors while iterating?如何在迭代时报告和修复错误?
【发布时间】:2022-12-05 05:28:37
【问题描述】:

我想遍历下面 raw_data 中的元素,并且

  • 存储f(x)的值
  • 当 f(x) 给出错误时,显示错误消息并存储此消息
  • 修复了由于类型引起的错误,即“四”而不是 4

可以同时做这三件事吗?

import math
import sys

raw_data = [5,"four", -3,2,1]

def f(x):
    return math.log(x)

到目前为止我所拥有的是:

import math
import sys

raw_data = [5,"four", -3,2,1]

def f(x):
    return math.log(x)

for x in raw_data:
    try:
        print(f(x))
    except:
        print("error:",sys.exc_info()[0])

这给了我一个列表结果:

1.6094379124341003
error: <class 'TypeError'>
error: <class 'ValueError'>
0.6931471805599453
0.0

我会怎样

a) 在没有错误的地方存储 f(x) 的值

b) 哪里有错误,报告并存储错误信息

c) 更正类型错误?

非常感谢你提前

【问题讨论】:

  • 您打算如何修复错误?

标签: python loops iteration typeerror store


【解决方案1】:

假设您想将函数结果和错误消息存储在两个不同的列表中,我建议创建两个列表并附加到您的 try/except 中的一个或另一个。使用字典在特定字符串和它们的数字等价物之间进行翻译。

results = []
errors = []
num_names = {
    'four': 4,
}

for x in raw_data:
    x = num_names.get(x, x)
    try:
        results.append(f(x))
    except Exception as e:
        errors.append(str(e))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2013-12-20
    相关资源
    最近更新 更多