在 Python 中缩短条件
Shortening conditional in Python
我想知道以下条件语句最简洁的写法是什么?
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
这是我要说的清晰代码:
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) 压缩在一起,将您的所有条件放在 list/generator 中。
然后我们用 all(conds)
检查所有条件是否为真,如果 True
.
则执行
如果您想要 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')
这可能更清楚,或者至少更容易看出您希望值介于:
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]
简化多个 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
我想知道以下条件语句最简洁的写法是什么?
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
这是我要说的清晰代码:
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) 压缩在一起,将您的所有条件放在 list/generator 中。
然后我们用 all(conds)
检查所有条件是否为真,如果 True
.
如果您想要 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')
这可能更清楚,或者至少更容易看出您希望值介于:
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]
简化多个 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