使用And运算符为每个非无参数添加函数 [英] Adding Function for Every non-None Parameters with And Operator
问题描述
我想用和
将具有非无参数的函数组合在一起.假设我具有此功能: 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 and
ing these arguments, you can just use all()
and filter out the None
s:
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屋!