缩短两个变量的IF条件(相同比较)

2024-05-23 17:46:25 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我需要做的:

if ((a<100 and a>-100) and (b<100 and b>-100)):

#i.e., if both a and b lie in the interval (-100,100)

我想知道我能不能用一个简短的方式写这个。你知道吗

UPD:找到了以下方法。有比这个短的吗?(不过,这对于2个变量来说并不是很短)

if all((x > -100 and x < 100) for x in (a,b))

Tags: andthe方法inforif方式all
3条回答

你可以写

(a<100 and a>-100)

作为

-100 < a < 100

因此,您可以将表达式简化为

if -100 < a < 100 and -100 < b < 100:
    #Do things

因为你的极限是对称的,所以进一步的简化可以使用:

abs(a) < 100

这个怎么样:

if abs(a) < 100 and abs(b) < 100:
    # do work

或者

if all(abs(x) < 100 for x in (a,b))

这是我能说的最简洁的;-)

from operator import lt

all(map(lt, [a,-a,b,-b], [100]*4))

相关问题 更多 >