首页 > 解决方案 > 通过减少 if else 语句的数量来优化代码

问题描述

我正在为存储数千种不同颜色代码的库编写代码,并根据标准化的传递值选择颜色。以下是仅返回十种颜色的参考代码:

colour_coding=[]
i=0
step=0
while i<1000:
    temp=(step,0,0)
    colour_coding.append(temp)
    step+=0.001
    i+=1

def color_code(value):
    if value>=0 and value<=0.1:
        return color_code[0]
    elif value>0.1 and value<=0.2:
        return color_code[1]
    elif value>0.2 and value<=0.3:
        return color_code[2]
    elif value>0.3 and value<=0.4:
        return color_code[3]
    elif value>0.4 and value<=0.5:
        return color_code[4]
    elif value>0.5 and value<=0.6:
        return color_code[5]
    elif value>0.6 and value<=0.7:
        return color_code[6]
    elif value>0.7 and value<=0.8:
        return color_code[7]
    elif value>0.8 and value<=0.9:
        return color_code[8]
    else:
        return color_code[9]

现在我想要更精确的颜色,因为我必须写大约一千,否则这将是一项乏味和重复的工作,有什么办法可以优化这段代码吗?

标签: python-3.xoptimization

解决方案


不是解决方案,但这可能会给您一个想法:

 import math
 def color_code(value):
    return color_code[math.ceil(value * 10) -1]

此代码应该能够处理上述代码中的所有条件。您需要添加条件来处理 index > 9 的情况。

对于千次迭代,您只需要找到正确的数学函数来根据范围计算正确的索引。

几个警告:

  1. 我不是 python 开发人员,所以我的语法可能不正确。
  2. 您的 if 条件可能不需要大于检查。else if 将保证第一个匹配的条件将自动排除所有其他条件。

即你应该能够摆脱这样的代码:

def color_code(value):
    if value<=0.1:
       return color_code[0]
    elif value<=0.2:
       return color_code[1]
etc.

推荐阅读