缩短Python中的条件

时间:2018-05-22 19:07:36

标签: python if-statement conditional

我想知道编写以下条件的最简洁方法是什么?

if not 0.01 < parameters[0] <1. or not 0.01 < parameters[1] <2. or not 0.01 < parameters[2] <0.25 or not 0.01 < parameters[3] <0.25 or not 0.01 < parameters[4] < 0.2
    #do something

4 个答案:

答案 0 :(得分:4)

这是一个明确的代码我会说:

parameters = [0,0,0,0,0]

LBS = [.01, .01, .01, .01, .01]
UBS = [1., 2., .25, .25, .2]

conds = (not (LB < param < UB) for param, LB, UB in zip(parameters, LBS, UBS))

if all(conds):
    # Action

或更有效:

conds = (LB < param < UB for param, LB, UB in zip(parameters, LBS, UBS))

if not any(conds):
    # Action

或者:

if not any(LB < param < UB for param, LB, UB in zip(parameters, LBS, UBS)):

<强>解释

让我们将你的所有条件放在一个列表/生成器中,将你的参数,下界(LBS)和上界(UBS)压缩在一起。

然后我们检查所有conds是否为True all(conds)并执行True

答案 1 :(得分:1)

简化多个or的快捷方法是使用内置的python any。在这种情况下,你会得到这样的东西:

upper_bounds = [1, 2, 0.25, 0.25, 0.2]
if any([not 0.01 < parameters[i] < up for i, up in enumerate(upper_bounds)]):
    # do something

答案 2 :(得分:0)

如果你想要一个clear解决方案,我会选择Anton在我上面写的东西。但是,问题要求最多succinct。这就是我想出来的。

if len(list(filter(lambda p: p[1] <= 0.01 or p[1] >= [1,2,.25,.25,.2][p[0]],enumerate(parameters)))) != 0:
    print('Do something')

答案 3 :(得分:0)

这可能更清楚,或者至少更容易看出你想要的值是什么:

floor= 0.01
array = [1,2,0.25,0.25,0.2,0.01]
if not floor < parameters[0] <array[0] 
or 
not floor < parameters[1] <array[1] 
or 
not floor < parameters[2] <array[2] 
or 
not floor < parameters[3] <array[3] 
or 
not floor < parameters[4] < array[4]