Python否定布尔函数

时间:2017-03-02 17:17:52

标签: python standard-library

使用lambda函数可以很容易地否定python布尔函数,但它有点冗长且难以阅读的东西如此基本,例如:

def is_even(n):
    return n % 2 == 0

odds_under_50 = filter(lambda x: not is_even(x), range(50))

我想知道在标准库中是否有一个函数可以执行此操作,这可能看起来像:

odds_under_50 = filter(negate(is_even), range(50))

4 个答案:

答案 0 :(得分:9)

据我所知,没有内置功能,或者是一个流行的库。

尽管如此,你可以轻松自己写一个:

from functools import wraps

def negate(f):
    @wraps(f)
    def g(*args,**kwargs):
        return not f(*args,**kwargs)
    return g

然后您可以使用:

odds_under_50 = filter(negate(is_even), range(50))

negate函数适用于给定函数的任意数量的参数:如果您已定义is_dividable(x,n=2)。然后negate(is_dividable)是一个带有两个参数(一个可选)的函数,它也接受这些参数。

答案 1 :(得分:2)

如果是filter,您可以使用ifilterfalse中的itertools

答案 2 :(得分:2)

您可以创建装饰器:

@negate
def is_odd(x):
    return x % 2 == 0

此装饰器也可以与@negate一起使用。

Where

答案 3 :(得分:1)

使用 funcycompose 函数,您可以像这样否定函数:

import operator

import funcy

is_odd = funcy.compose(operator.not_, is_even)

如果你想让它更具可读性:

def negate(func):
    return funcy.compose(operator.not_, func)

is_odd = negate(is_even)

# or without creating the function directly
print(negate(is_even)(5))

funcy library has a lot of other useful functions for functional programming