如何优化使用字典替代多if-elif判断温度描述的Python代码效率
温度匹配代码优化方案
原有实现除了性能问题外,还存在两个小问题:函数名deternmine拼写错误,且缺失40℃~41℃的区间覆盖,会导致该范围温度返回None。性能问题的根源如下:
- 每次调用函数都会重复生成10个区间列表,产生大量不必要的内存开销和初始化耗时
- 遍历所有字典键值对做
temp in 列表判断,列表的in操作是线性遍历,整体时间复杂度为O(n),n为区间数量,区间越多性能越差
以下是不同场景的优化方案:
方案1:bisect二分查找实现(最通用,性能最优)
适合区间数量多、划分细的场景,时间复杂度稳定O(log n),几乎不受区间数量影响,比原实现性能高几十到上百倍。
import bisect # 常量放到函数外部,只初始化一次 TEMP_THRESHOLDS = [-20, 0, 6, 11, 16, 21, 26, 31, 36, 40, 46] TEMP_DESCRIPTIONS = [ 'FREEZING', 'very cold', 'cold', 'chilly', 'cool', 'warm', 'hot', 'very hot', 'dangerously hot', 'extremely dangerously hot' ] def determine_temp(temp): temp_val = int(temp.replace('°', '').strip()) # 超出范围可自定义返回值 if temp_val < TEMP_THRESHOLDS[0] or temp_val >= TEMP_THRESHOLDS[-1]: return 'out of range' idx = bisect.bisect_right(TEMP_THRESHOLDS, temp_val) - 1 return TEMP_DESCRIPTIONS[idx]
方案2:预构建温度映射字典(当前场景最快,O(1)查找)
你的场景温度范围只有-20℃~45℃,范围极小,可以预先生成所有温度值对应的描述,每次查找直接取字典值,速度最快。
# 只初始化一次 TEMP_MAP = {} TEMP_RULES = [ (-20, 0, 'FREEZING'), (0, 6, 'very cold'), (6, 11, 'cold'), (11, 16, 'chilly'), (16, 21, 'cool'), (21, 26, 'warm'), (26, 31, 'hot'), (31, 36, 'very hot'), (36, 40, 'dangerously hot'), (40, 46, 'extremely dangerously hot') ] for low, high, desc in TEMP_RULES: for t in range(low, high): TEMP_MAP[t] = desc def determine_temp(temp): temp_val = int(temp.replace('°', '').strip()) return TEMP_MAP.get(temp_val, 'out of range')
方案3:字典内置判断函数(符合字典内置函数的需求)
如果希望用字典结构维护逻辑,可以把值换成判断函数,避免生成大量列表,判断速度比原实现快很多。
# 只初始化一次 TEMP_RULES = { 'FREEZING': lambda x: -20 <= x < 0, 'very cold': lambda x: 0 <= x < 6, 'cold': lambda x: 6 <= x < 11, 'chilly': lambda x: 11 <= x < 16, 'cool': lambda x: 16 <= x < 21, 'warm': lambda x: 21 <= x < 26, 'hot': lambda x: 26 <= x < 31, 'very hot': lambda x: 31 <= x < 36, 'dangerously hot': lambda x: 36 <= x < 40, 'extremely dangerously hot': lambda x: 40 <= x < 46 } def determine_temp(temp): temp_val = int(temp.replace('°', '').strip()) for desc, condition in TEMP_RULES.items(): if condition(temp_val): return desc return 'out of range'
内容的提问来源于stack exchange,提问作者lizardowl5151
相关产品推荐
相关产品推荐

