python - 不使用 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 条这样的语句,它们有不同的单、双或三条件。有更好的编码实践吗?
解决方案
一个很好的做法,在不删除 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是否支持多个条件。
推荐阅读
- python - CSV 到 Python 字典
- c# - 在 C# 中有什么方法可以限制 int 变量的范围吗?
- java - 找不到文件 (getResource)
- android - 我正在做一些计算,但无法将字符串解析为 int 甚至是 float
- php - 如何将表单的 $id 传递给另一个表单
- mysql - Rails:将外键添加到多列的主键
- javascript - 如何从 CSS 获取链接文本到字符串对象?
- sql - 如何在不破坏参照完整性 SQL Server 的情况下将来自不同 tbls 的地址收集到一个中
- java - 如何在 Lubuntu 中使用 PC NAME 永久挂载 Windows 共享文件夹?
- python-3.x - 针对单个问题的重复插入请求