首页 > 解决方案 > 如何将许多 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'

仅在退货声明中

标签: python-3.x

解决方案


如果 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')

推荐阅读