简化if ... elif..else条件 [英] Simplifying `if...elif..else` conditions

查看:63
本文介绍了简化if ... elif..else条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有多个条件(嵌套和/或其他),且布尔值( False True )输出;如何进一步简化代码,使其更高效,更全面,更优雅?

If I have multiple conditions (nested and/or otherwise) with boolean (either False or True) outputs; how could I further simplify the code and make it more efficient, comprehensive, and elegant?

例如,在以下情况下:

if condition_1:
    if condition_2:
        # do one thing
        pass
    elif condition_3:
        # do another thing
        pass
    else:
        # do a third thing
        pass

elif condition_2:
    if condition_3:
        # do a fourth thing
        pass

以此类推.

这是我的考试项目,因此没有得到太多帮助,我将尝试解释我的代码应该做什么.我基本上想浏览一个数据集,寻找不同的东西.让我们说它是一个字典,像这样:

It's a exam project of mine, so not get too much help, I'll try and explain what my code should do. I basically want to go through a dataset, looking for different things. Lets say its a dictionary, like this:

myDict = {'a': ['b', 'c'], 'b': ['c', 'd']}

如果我听了字典:

for item, element in myDict.items():
    for letter in element:
        if letter == 'd':
            dflag = True
        if letter == 'c':
            cflag = True

    if cflag:
        if dflag:
            print('cd!')
        else:
            print('only c')

推荐答案

如果有效地使用'if','elif'和'else'也不错.但总的来说,您问题的答案实际上取决于个人情况.

Using 'if', 'elif', and 'else' is not bad if it is done efficiently. But in general, the answer to your question would really depend upon individual circumstances.

但是,要做到这一点,一种方法是将您的条件放在 dict 中(如您自己在标签中突出显示的那样).

Having said that, however, one way to do it would be to put your conditions inside a dict (as highlighted by yourself in the tags).

以下是一些示例:

conditions = {
    1: 'One',
    2: 'Two',
    3: 'Three',
    4: 'Four',
    5: lambda x: x**2  # Can be substituted with actual functions defined elsewhere.
}

x = 3

if x in conditions.keys():
    print(conditions[x])

返回:

Three

,或者在使用函数的情况下:

or in the case of a function:

x = 5

if x in conditions.keys():
    func = conditions[x]
    print(func(x))

返回:

25

使用类似于 switch ... case 的功能:

要使其更加清晰,并具有类似 switch ... case 语句的内容,您可以执行以下操作:

Using a function to resemble switch...case:

To make it even clearer, and have something like a switch...case statement, you can do this:

def switch(case):
    conditions = {
        1: 'One',
        2: 'Two',
        3: 'Three',
        4: 'Four',
        5: lambda x: x**2  
    }

    return condition[case] if case in conditions else False

运行方式如下:

>>> print(switch(2))
2

或不存在的项目:

>>> print(switch(6))
False

您的示例的实现方式

switch ... case 函数装饰器(包装器)

因此,为了解决您添加的示例,我们可以执行以下操作:

Implementation on your example:

switch...case function decorator (wrapper)

So to address the example you have added, we can do as follows:

首先,我们需要一个通用的开关/外壳装饰器:

First we need a general switch/case decorator:

def switch_case(switch):
    def switcher(func):
        def case(case):
            return switch[case](case) if case in switch else None
        return case 
    return switcher

然后我们需要一本关于条件的字典,这是您的示例中给出的字典:

Then we need a dictionary of our conditions, which are the one given in your example:

# Define the conditions in a dict.
conditions = {
    'd': lambda x: True if 'd' else False,  # You can say: True if 'a' or 'b' else False
    'c': lambda x: True if 'c' else False  
}

现在,我们将根据您的条件创建一个修饰的开关盒功能:

Now we Create a decorated switch-case function based on your conditions:

@switch_case(conditions)
def my_conditions(case):
    return case

然后我们指定元素,或从文件,数据库或其他任何东西中读取它们:

Then we specify the elements, or read them from a file, database or anything:

# Elements to be tested as string.
# It can be any flattened (not nested) iterable (str, tuple, list, numpy.array, etc.)
myDict = {'a': ['b', 'c'], 'b': ['c', 'd']}
elements = sum(myDict.values(), [])  # Returns a flattened lists of values. 

根据条件(生成器对象)评估元素.

Evaluate the elements based on the conditions (generator object).

verdicts = map(my_conditions, elements)

将元素匹配到相应的评估结果(生成器对象).

Match the elements to the corresponding evaluation results (generator object).

status = zip(elements, verdicts)

现在,我们可以积极地调节输出了(丢弃 None vlues)并创建一个 dict ,其中键是元素,值是其条件的状态

Now we can positively regulate the outputs (discard None vlues) and create a dict in which the keys are the elements, and the values are the status of their conditions.

passed = {key+'flag': val for key, val in status if val is not None}

print(passed)
# output: {'cflag': True, 'dflag': True}

作为变量添加到名称空间

这时,您可以按原样使用dict;但是,如果您坚持将其添加到名称空间,则方法如下:

Add as variables to the namespace

At this point, you can use the dict as is; however, if you insist on adding it to the namespace, here is how:

# Rename values and add them to the name space.
locals().update(passed)

测试

最后,让我们测试并确保这些值存在于本地名称空间中(请注意,我们之前没有实现任何这些名称).因此,如果条件为序列中的特定字符返回了 True 值,则将创建一个变量:

Test

Finally, let's test and ensure the values exist in the local namespace (notice that we haven't implemented any of these names before). So, if the condition returned a True value for the particular character in the sequence, a variable would have been created:

>>> print(dflag)  # We had 'd' in `myDict` values.
True

另一方面,如果条件返回 None ,则命名空间中将没有任何值.

On the other had, if the condition returned None, there will be no value in the namespace.

>>> print(aflag)  # We didn't have 'a' in `myDict` values.
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-25-26f7e9594747> in <module>()
     24
---> 25 print(aflag)

NameError: name 'aflag' is not defined

注意:在现有结构下,如果条件返回 False ,则会在命名空间中创建变量 并分配值为 False .

Note: Under the existing structure, if the condition returns False, a variable will be created in the namespace and assigned a value of False.

希望这会有所帮助.

这篇关于简化if ... elif..else条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆