简体   繁体   English

如何在不不断重复代码的情况下使捕获异常为变量分配特定值?

[英]How can I make catching exceptions assign a variable a certain value without constantly repeating the code?

I'm going to clarify.我要澄清一下。

I'm logging 6 different variables and some of them have errors (what kind of error doesn't matter).我正在记录 6 个不同的变量,其中一些有错误(什么样的错误无关紧要)。 When that error occurs, I just want that specific variable to be put to "NA".发生该错误时,我只想将该特定变量设置为“NA”。

Here's an idea of what I mean:这是我的意思的想法:

myDict = []
for i in data:
    try:
        eye = ...
        nose = ...
        mouth = ...
        ear = ...
        hair = ...
        tongue = ...
        
        myDict.append([eye, nose, mouth, ear, hair, tongue])

   except eye:
        eye = "NA"
        myDict.append([eye, nose, mouth, ear, hair, tongue])
  
   except nose:
        nose = "NA"
        myDict.append([eye, nose, mouth, ear, hair, tongue])

   except mouth:
        mouth = "NA"
        myDict.append([eye, nose, mouth, ear, hair, tongue])

   ...

Do I have to do an "except" for every single variable?我必须为每个变量做一个“例外”吗? Is there some way I could just do "except whatever variable has error, assign its value to "NA" and append normally"?有没有什么办法我可以做“除了任何变量有错误,将其值分配给“NA”并正常附加”?

I also don't know what happens if there's an error in more than 1 variable.我也不知道如果超过 1 个变量有错误会发生什么。

The fundamental idea is: "if there's an error for a variable(S), just assign it/them the value "NA" and keep appending.基本思想是:“如果变量(S)有错误,只需为它/它们分配值“NA”并继续附加。

Here's an example of an approach that will do what you're asking.这是一个可以满足您要求的方法示例。

First some comments:首先是一些评论:

  • You have used the term "error", but your sample code uses try/except, so I will assume that each "error" results in an exception being raised.您使用了术语“错误”,但您的示例代码使用了 try/except,因此我假设每个“错误”都会导致引发异常。
  • In the code below, I use an artificially simplified scenario in which the assignment to each variable has the possibility of raising an exception with a similar name, and I have created these as user-defined exceptions;在下面的代码中,我使用了一个人为简化的场景,其中对每个变量的赋值都有可能引发具有相似名称的异常,并且我将这些异常创建为用户定义的异常; in reality, you may not need to define these and would instead replace the parenthesized exception types in the sample code with the actual exceptions that you want to catch.实际上,您可能不需要定义这些,而是​​将示例代码中带括号的异常类型替换为您想要捕获的实际异常。
  • You have something called myDict which is actually a python list;你有一个叫做myDict的东西,它实际上是一个 python 列表; I will rename this result in the code below to avoid confusion.我将在下面的代码中重命名这个result以避免混淆。

The logic of the code below can be summarized as:下面代码的逻辑可以概括为:

  • Instead of assigning directly to named variables (as in the code in your question), iterate through a list of variable tags (strings like 'eye', 'nose', etc.) in an inner loop which has a try/except block inside it;与其直接分配给命名变量(如您问题中的代码),不如在内部循环中迭代变量标签列表(字符串,如“eye”、“nose”等),该内部循环中有一个 try/except 块它;
  • Within this inner list, do the work for the given tag (the same work that would be done by eye = ... or mouth = ... in your question) and append the result to a list L , unless an exception is raised, in which case the try block instead appends "NA" to L ;在此内部列表中,为给定标签执行工作(与您的问题中eye = ...mouth = ...完成的工作相同)并将结果附加到列表L ,除非引发异常,在这种情况下,try 块改为将“NA”附加到L
  • This means that whether or not there are errors (more accurately, whether or not exceptions are raised), L will have a value appended to it for each variable tag;这意味着无论是否有错误(更准确地说,是否引发异常), L都会为每个变量标签附加一个值;
  • At the end of the inner loop, append L to the result.在内部循环结束时,将L附加到结果中。

Here is the sample code:这是示例代码:

class eye_exception(Exception):
    pass
class nose_exception(Exception):
    pass
class mouth_exception(Exception):
    pass
class ear_exception(Exception):
    pass
class hair_exception(Exception):
    pass
class tongue_exception(Exception):
    pass


def getValueForEye(i):
    return "eye_value" + str(i)
def getValueForNose(i):
    return "nose_value" + str(i)
def getValueForMouth(i):
    if i % 3 == 0:
        raise mouth_exception()
    return "mouth_value" + str(i)
def getValueForEar(i):
    return "ear_value" + str(i)
def getValueForHair(i):
    if i % 3 != 0:
        raise hair_exception()
    return "hair_value" + str(i)
def getValueForTongue(i):
    return "tongue_value" + str(i)

data = [1, 2, 3]

result = []
for i in data:
    L = []
    for key in ['eye', 'nose', 'mouth', 'ear', 'hair', 'tongue']: 
        try:
            match key:
                case 'eye':
                     value = getValueForEye(i)
                case 'nose':
                     value = getValueForNose(i)
                case 'mouth':
                     value = getValueForMouth(i)
                case 'ear':
                     value = getValueForEar(i)
                case 'hair':
                     value = getValueForHair(i)
                case 'tongue':
                     value = getValueForTongue(i)
            L.append(value)
        except (eye_exception, nose_exception, mouth_exception, ear_exception, hair_exception, tongue_exception):
            L.append("NA")
    result.append(L)

Sample result :样本result

['eye_value1', 'nose_value1', 'mouth_value1', 'ear_value1', 'NA', 'tongue_value1']
['eye_value2', 'nose_value2', 'mouth_value2', 'ear_value2', 'NA', 'tongue_value2']
['eye_value3', 'nose_value3', 'NA', 'ear_value3', 'hair_value3', 'tongue_value3']

Alternatively, if you are using a version of python that does not support the match/case construct, or you simply prefer not to use it, you can replace the loop above with this code which uses a dictionary to map from variable tag to function:或者,如果您使用的 python 版本不支持 match/case 构造,或者您只是不想使用它,您可以使用以下代码替换上面的循环,该代码使用字典从变量标记映射到函数:

funcDict = {
    'eye':getValueForEye, 
    'nose':getValueForNose, 
    'mouth':getValueForMouth, 
    'ear':getValueForEar, 
    'hair':getValueForHair, 
    'tongue':getValueForTongue
}
for i in data:
    L = []
    for key, func in funcDict.items(): 
        try:
            value = func(i)
            L.append(value)
        except (eye_exception, nose_exception, mouth_exception, ear_exception, hair_exception, tongue_exception):
            L.append("NA")
    result.append(L)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM