不使用 if 语句的数字比较

Number comparison without using if statements

我有很多比较要做。我为此使用了多个 if 语句,但数量太多,我不确定这是否是最佳编码实践。我可以用什么来代替它们?

例如,我有这个:

if ((ANum==2) and (Action==1)):
    print ("*some text*")
if ((ANum==2) and (Action==1) and (2.5<=Freq<=4)):
    print("*some text*")
if ((ANum==2) and (1<=FreqMagnitude<=6.5)):
    print("*some text*")
if ((ANum==1) and (Action==0) and (4.5>Freq)):
    print("*some text*")

我有大约 20 个这样的语句,带有不同的单条件、双条件或三条件。有没有更好的编码实践?

一个很好的做法,在不删除 if 的情况下,它 有机一点:

来自这里:

if ((ANum==2) and (Action==1) and (2.5<=Freq<=4)):
    print("*some text*")
if ((ANum==2) and (1<=FreqMagnitude<=6.5)):
    print("*some text*")
if ((ANum==1) and (Action==0) and (4.5>Freq)):
    print("*some text*")

为此:

if(Action==1):
    if(ANum==2):
        if(1<=FreqMagnitude<=6.5):
            print("*some text*")
        if(2.5<=Freq<=4):
            print("*some text*")
if(Action==0):
    if(ANum==1):
        if(4.5>Freq):
            print("*some text*")

因此,如果您有另一个操作条件 ==1 和 ANum == 2,您只需在“ANum==2”验证之后添加一个新条件。

这里的提示是:确定“通用”标准并将它们放在顶部,例如“从一般标准到特定标准”。

如果你不喜欢这个,你可以尝试“switch case”,但我不知道switch是否支持多个条件。