You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何精简Python中用if elif实现月份匹配的冗余代码?

代码优化实现

优化思路

  • 移除冗余的多分支if-elif判断,使用「月份-截取长度」的映射字典实现规则配置,后续调整各月份逻辑仅需修改映射表即可,支持全12个月的自定义处理
  • 修正原函数的局部变量赋值不生效问题:原函数内对参数d的赋值仅作用于函数局部作用域,外部传入的dict_items不会被修改,优化后通过return返回处理后的结果
  • 若多个月份对应相同的截取规则,可直接批量配置映射关系,进一步精简代码

优化后完整代码

from datetime import date

a_dictionary = {"name" : "John", "age" : 35, "height" : 65}
dict_items = a_dictionary.items()

def month_selct(d):
    # 配置各月份对应的切片长度,可按需自定义调整
    month_cut_map = {
        # 1-3月统一取前2个元素
        1:2, 2:2, 3:2,
        # 4-6月统一取前1个元素
        4:1, 5:1, 6:1,
        # 7-12月取全部元素
        7:3, 8:3, 9:3, 10:3, 11:3, 12:3
    }
    cut_length = month_cut_map.get(date.today().month, 3) # 缺省默认取全部
    return list(d)[:cut_length]

# 调用函数获取处理后的结果
processed_items = month_selct(dict_items)
print(processed_items)

更精简的同规则批量配置写法

如果同一规则对应连续月份,可以用推导式生成映射表,进一步减少重复配置:

def month_selct(d):
    # 批量生成映射规则:1-3月取2个,4-6月取1个,其余取3个
    month_cut_map = {
        **{m:2 for m in range(1,4)},
        **{m:1 for m in range(4,7)},
        **{m:3 for m in range(7,13)}
    }
    cut_length = month_cut_map.get(date.today().month, 3)
    return list(d)[:cut_length]

内容的提问来源于stack exchange,提问作者user17031311

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:15:01