使用And运算符为每个非无参数添加函数 [英] Adding Function for Every non-None Parameters with And Operator

查看:48
本文介绍了使用And运算符为每个非无参数添加函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用将具有非无参数的函数组合在一起.假设我具有此功能:
def foo(a,b,c)对于每个非参数,我想调用一个函数,例如 bar 并与 and 链接.但是,如果所有参数都不是 None ,那么在此示例中,结果将具有以下6种组合:

I want to combine functions with non-None parameters with and. Suppose I have this function:
def foo(a,b,c) For every non-None parameter, I want to call a function, for example bar and linked with and. But if all of the parameters are None, So, in the example, the result will be having 6 combinations like this:

if a is not None and b is not None and c is not None:
    return bar(a) and bar(b) and bar(c)
elif a is None and b is not None and c is not None:
    return bar(b) and bar(c)
elif a is not None and b is None and c is not None:
    return bar(a) and bar(c)
elif a is not None and b is not None and c is None:
    return bar(a) and bar(b)
elif a is None and b is None and c is not None:
    return bar(c)
elif a is None and b is not None and c is None:
    return bar(b)
elif a is not None and b is None and c is None:
    return bar(a)
else:
    return True

如何在不列出所有可能的参数组合的情况下执行此操作?例如,可以做这样的事情吗?( + = 表示)

How do I do this without listing all of the possible combinations of parameters? For example, is it possible to do something like this? (+= symbolizes and)

func = ...
if a is not None:
    func += bar(a)
if b is not None:
    func += bar(b)
if c is not None:
    func += bar(c)
if all of them wrong:
    return True
else:
    do func

推荐答案

如果您想要这些参数的结果,则可以使用 all()和过滤掉 None s:

If you want the result of anding these arguments, you can just use all() and filter out the Nones:

def bar(n):
    return n

def foo(a,b,c):
    return all(bar(arg) for arg in [a, b, c] if arg is not None)

foo(None, True, True)
# True

foo(False, True, None)
# False

这篇关于使用And运算符为每个非无参数添加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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