python-3.x - 评估返回 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”编写第二个函数,但这看起来很丑陋,所以我想要一些可以评估所有这些并返回值的东西。我没有足够的编写方法的经验,这些方法接受多个输入以及多个不同的输入,因此我将不胜感激。
解决方案
您可以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
推荐阅读
- java - 如何删除活动中的数据?
- google-analytics - ecommerce:addItem 是跟踪电子商务跟踪所必需的
- javascript - 如何应用加载更多以获取 WordPress 模板中的自定义帖子
- python - 我如何在 python 中一次又一次地调用 save_loc 函数
- google-cloud-platform - Google Compute Engine (GCE) - CentOS 映像损坏(无法更新/升级)
- devexpress - 更改 DevExpress MVC 仪表板默认调色板
- java - 通过 Class.forName() 方法调用进行动态注入总是有害的吗?
- rasa-nlu - Rasa 服务器的最低系统要求和并行客户端请求数量的限制?
- xml - 将注释xml转换为Python中的文本
- python - 使用 Tkinter 和 Speech to Text 进行线程化