python-3.x - 如何将许多 If else 语句作为回报
问题描述
我很好奇是否有办法执行这样的代码:
在数组中我们有 True 和 False 语句在 op 我们有 'AND' 或 'OR' 或 'XOR'
def logical_calc(array, op):
if array.count(False)<1 and op=="AND":
return 1
elif array.count(True)>0 and op=='OR':
return 1
elif array.count(True)%2!=0 and op=='XOR':
return 1
else:
return 0
这样:
def logical_calc(array, op):
return True if array.count(False)<1 and op=="AND"
elif array.count(True)>0 and op=='OR'
elif array.count(True)%2!=0 and op=='XOR'
仅在退货声明中
解决方案
如果 3 个条件中的任何一个为 True,您想要返回 True,要实现这一点,您需要完全消除 if 语句并将返回值写为布尔表达式;
def logical_calc(array, op):
return (array.count(False)<1 and op=="AND") or
(array.count(True)>0 and op=='OR') or
(array.count(True)%2!=0 and op=='XOR')
推荐阅读
- c++ - C++ 线程安全队列
- android - 使用接口处理 AsyncTask Activity 在 Android Studio 中显示为错误,但在运行时不显示
- javascript - 使用基本方法Javascript让单个数字相互相乘直到达到单个数字
- spring-boot - Spring JPA - 在运行时替换数据源
- python - Python 请求未正确下载 pdf
- java - Apache Beam KafkaIO 处理卡在 readfromkafka
- java - 如何将另一个类对象添加到列表中
- python - 在 python 中从 cURL GET 请求保存 .zip 文件
- php - 检查数据库中是否存在值,然后转到另一个 php 页面
- pip - 在 Catalina 下使用 pip 安装 Jupyter