如何利用列表或字典简化重复的Python月份判断代码?
优化冗余月份判断代码的可行思路
方法一:通过数学计算推导baldat值
观察你给出的对应规则:输入月份+2就是baldat的月份,当结果≤12时,baldat年份为输入年份-1;当结果>12时,baldat年份为输入年份,月份则减去12(比如11月→13→年份不变,月份1;12月→14→年份不变,月份2)。这种规律可以直接用计算实现,无需重复判断:
@staticmethod def _keep_leads_baldat(leads_aggregated, month, year): # 计算baldat的月份和年份 baldat_month = month + 2 if baldat_month <= 12: baldat_year = year - 1 else: baldat_year = year baldat_month -= 12 # 格式化为两位字符串(如3→"03") baldat_month_str = f"{baldat_month:02d}" baldat_full = f"{baldat_year}{baldat_month_str}" # 打印信息 print(f"proces date - year : {year}, month : {month}, baldat : {baldat_full}") print(f"{PROCESS_DATE}{year}{MONTH}{month}, {BALDAT}{baldat_full}") # 过滤数据 leads_aggregated_final = leads_aggregated.where(substring(col("BALDAT"), 1, 6) == baldat_full) return leads_aggregated_final
方法二:用字典映射月份与baldat对应关系
如果后续月份对应关系可能变化、或者规则不那么线性,用字典存储映射关系会更灵活,维护起来更方便:
@staticmethod def _keep_leads_baldat(leads_aggregated, month, year): # 定义每个输入月份对应的(年份偏移量, baldat月份字符串) month_baldat_map = { 1: (-1, "03"), 2: (-1, "04"), 3: (-1, "05"), 4: (-1, "06"), 5: (-1, "07"), 6: (-1, "08"), 7: (-1, "09"), 8: (-1, "10"), 9: (-1, "11"), 10: (-1, "12"), 11: (0, "01"), 12: (0, "02") } # 获取对应配置,同时处理无效月份的情况 year_offset, baldat_month_str = month_baldat_map.get(month, (None, None)) if year_offset is None: raise ValueError(f"Invalid month value: {month}") baldat_year = year + year_offset baldat_full = f"{baldat_year}{baldat_month_str}" # 打印信息 print(f"proces date - year : {year}, month : {month}, baldat : {baldat_full}") print(f"{PROCESS_DATE}{year}{MONTH}{month}, {BALDAT}{baldat_full}") # 过滤数据 leads_aggregated_final = leads_aggregated.where(substring(col("BALDAT"), 1, 6) == baldat_full) return leads_aggregated_final
两种方法对比
- 方法一适合规则固定且有明确数学逻辑的场景,代码更简洁,无需维护额外映射表;
- 方法二适合对应关系可能变动、或者规则复杂的场景,修改对应关系只需调整字典,可读性和扩展性更强。
内容的提问来源于stack exchange,提问作者user22245761
相关产品推荐
相关产品推荐

