简体   繁体   English

在没有if的情况下通过多个条件传递变量?

[英]Passing variable through multiple conditions without if?

What I'm trying to do is to pass a variable through a function that has a list of multiple lambda condition functions.我想要做的是通过 function 传递一个变量,该变量具有多个 lambda 条件函数的列表。

This function should behave by either returning 1 if all conditions are met or stopping the "iteration" and returning which conditions was not met.这个 function 应该通过在满足所有条件时返回 1 或停止“迭代”并返回未满足的条件来表现。

Something like this:是这样的:

def is_conditions_met(y):

    conditions = (lambda x: 1 if isinstance(x, int) else return "Wrong type",
                  lambda x: 1 if x % 2 == 0 else return "Not even",
                  lambda x: 1 if x >= 40 else return "Less than 40")

    return all(conditions, y)

    >>> is_condition_met('foo')
    >>> ' Wrong type '

    >>> is_condition_met(14)
    >>> ' Less than 40 '

    >>> is_condition_met(42)
    >>> True

I think you should use IF, but use it more effective.我认为你应该使用 IF,但使用它更有效。 In you variation all 3 functions will be executed no matter what.在您的变体中,无论如何都会执行所有 3 个功能。 I suggest to check conditions step by step.我建议逐步检查条件。 For example, you don't need to execute 2 last functions if TYPE is not INT.例如,如果 TYPE 不是 INT,则不需要执行最后两个函数。 So my variation is:所以我的变化是:

def is_conditions_met(y):
    if not isinstance(y, int):
        return "Wrong type"

    # If type is INT we can check next condition and etc.
    if not y % 2 == 0:
        return "Not even"

    if not y >= 40:
        return "Less than 40"
    
    return True

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

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