首页 > 解决方案 > 评估返回 True 或 False 的多个函数的输出

问题描述

所以我遇到了这个有趣的问题。它基本上是很多函数在一个函数中返回 True 或 False,我希望辅助函数基于对其中的所有函数应用 AND 或 OR 逻辑来返回 True 或 False . 我知道这是一种糟糕的解释方式,所以让我们看看一些希望能更好地解释它的代码

#this is the first function that return True or False
def f(x):
    if x == 1:
        return True
    elif x == 0:
        return False
#this is the function that takes the first one and I want it to return either True or False based on an AND logic
def g(f):

    f(1)
    f(0)
    f(0)
    f(1)
    f(1)
    f(0)
    f(1)

现在我知道我可以在我调用的所有 f(x) 函数之间用“and”编写第二个函数,但这看起来很丑陋,所以我想要一些可以评估所有这些并返回值的东西。我没有足够的编写方法的经验,这些方法接受多个输入以及多个不同的输入,因此我将不胜感激。

标签: python-3.x

解决方案


您可以all对函数的变量参数 ( *args) 使用和理解:

>>> def f(x):
...     if x == 1:
...         return True
...     elif x == 0:
...         return False
... 
>>> def g(f, *args):
...     return all(f(x) for x in args)
... 
>>> g(f, 1, 0, 0, 1)
False
>>> g(f, 1, 1, 1)
True

推荐阅读