python-3.x - 通过减少 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]
现在我想要更精确的颜色,因为我必须写大约一千,否则这将是一项乏味和重复的工作,有什么办法可以优化这段代码吗?
解决方案
不是解决方案,但这可能会给您一个想法:
import math
def color_code(value):
return color_code[math.ceil(value * 10) -1]
此代码应该能够处理上述代码中的所有条件。您需要添加条件来处理 index > 9 的情况。
对于千次迭代,您只需要找到正确的数学函数来根据范围计算正确的索引。
几个警告:
- 我不是 python 开发人员,所以我的语法可能不正确。
- 您的 if 条件可能不需要大于检查。else if 将保证第一个匹配的条件将自动排除所有其他条件。
即你应该能够摆脱这样的代码:
def color_code(value):
if value<=0.1:
return color_code[0]
elif value<=0.2:
return color_code[1]
etc.
推荐阅读
- php - PHPSpreadsheet 适用于 XAMPP 但不适用于 Raspbian 上的 Apache
- c# - 如何在gridview项目上设置焦点编程?
- postgresql - 配置要发送到 GCP Stackdriver 的 Postgres 容器日志
- tfs - 将 DevOps 自定义计数器变量重置为 0
- javascript - Laravel5.8中重复ajax请求的问题
- php - 计算数组集中的唯一值
- java - JSON REST API:限制字段的可能值
- android - 在从 Firebase 加载数据的 Android RecyclerView 中,我想同时加载 admob 横幅广告
- python - 如何将响应路径键保存到变量中
- java - 无法转换包含“&”或“;”的 XML 字符串 到 JSON 对象