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

如何简化Python代码中冗长重复的IF/Else条件判断语句

代码优化方案

方案1:字典映射(最适配当前场景,上手成本低)

你当前的代码核心重复点是不同raceCheck值仅对应不同的文件名匹配规则,内部执行逻辑完全一致,因此可以用字典建立映射关系消除冗余判断:

import os
import fnmatch

# 提前建立race类型和匹配模式的映射关系
RACE_PATTERN_MAP = {
    'Race_1': '*1.pdf',
    'Race_2': '*2.pdf',
    'Race_3': '*3.pdf',
    'Race_4': '*4.pdf'
}

for file in os.listdir(src_dir):
    # 先判断raceCheck是否在支持的范围内
    if raceCheck not in RACE_PATTERN_MAP:
        print('I am here: ', file)
        continue
    # 拿到对应匹配规则
    target_pattern = RACE_PATTERN_MAP[raceCheck]
    if fnmatch.fnmatch(file, target_pattern):
        # 提前提取公共文件路径,避免重复计算
        file_full_path = os.path.join(src_dir, file)
        upload_to_aws_site1(file_full_path, 'official')
        upload_to_aws_site2(file_full_path)
        print(file)

优化点说明

  • 消除了多层嵌套的if/elif判断,后续新增Race类型只需在RACE_PATTERN_MAP中新增键值对即可,无需修改业务逻辑
  • 提取了重复的路径计算逻辑,减少重复代码
  • 代码可读性更高,维护成本更低

方案2:类封装(适合后续逻辑扩展场景)

如果后续不同Race需要扩展不同的处理逻辑(比如有的Race不需要上传到site2,有的需要额外打日志),可以用类封装的方式:

from abc import ABC, abstractmethod
import os
import fnmatch

class BaseRaceHandler(ABC):
    pattern: str
    
    @abstractmethod
    def process(self, file_full_path: str):
        pass

class Race1Handler(BaseRaceHandler):
    pattern = "*1.pdf"
    def process(self, file_full_path: str):
        upload_to_aws_site1(file_full_path, 'official')
        upload_to_aws_site2(file_full_path)

class Race2Handler(BaseRaceHandler):
    pattern = "*2.pdf"
    def process(self, file_full_path: str):
        upload_to_aws_site1(file_full_path, 'official')
        upload_to_aws_site2(file_full_path)

# Race3Handler、Race4Handler同理定义即可

# 建立race和对应处理类的映射
RACE_HANDLER_MAP = {
    'Race_1': Race1Handler,
    'Race_2': Race2Handler,
    'Race_3': Race3Handler,
    'Race_4': Race4Handler
}

for file in os.listdir(src_dir):
    if raceCheck not in RACE_HANDLER_MAP:
        print('I am here: ', file)
        continue
    handler = RACE_HANDLER_MAP[raceCheck]()
    if fnmatch.fnmatch(file, handler.pattern):
        file_full_path = os.path.join(src_dir, file)
        handler.process(file_full_path)
        print(file)

当前简单场景使用方案1即可满足需求,方案2适合业务逻辑复杂、后续有扩展需求的场景使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:15:03