首页 > 解决方案 > 不使用 if 语句的数字比较

问题描述

我有很多比较要做。我为此使用了多个 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 条这样的语句,它们有不同的单、双或三条件。有更好的编码实践吗?

标签: pythonif-statementconditional-statementscomparison

解决方案


一个很好的做法,在不删除 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”验证之后添加一个新的 if。

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

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


推荐阅读