Python negate boolean function

孤者浪人 提交于 2019-11-30 04:06:20

问题


A python boolean function can easily be negated with lambda functions, but it's a bit verbose and hard to read for something so basic, for example:

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

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

I'm wondering if there is a function to do this in the standard library, which might look like:

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

回答1:


As far as I know there is no builtin function for that, or a popular library that does that.

Nevertheless, you can easily write one yourself:

from functools import wraps

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

You can then use:

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

The negate functions works for an arbitrary amount of parameters of the given function: if you would have defined is_dividable(x,n=2). Then negate(is_dividable) is a function with two arguments (one optional) that would also accept these parameters.




回答2:


In case of filter you can use ifilterfalse from itertools.




回答3:


You can create a decorator:

def negate(function):
    def new_function(*args, **kwargs):
       return not function(*args, **kwargs)
return new_function


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

print is_even(1)
print is_even(2)

is_odd = negate(is_even)
print is_odd(1)
print is_odd(2)

This decorator can also be used with @negate.

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


来源:https://stackoverflow.com/questions/42561843/python-negate-boolean-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!