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

如何用OOP或设计模式简化Python中重复的多分支if逻辑?

简化Python多分支if语句的实用方案

你尝试的match语句更适合固定分支的模式匹配,对于这种参数化的重复逻辑,以下几种方案会更高效:

一、配置驱动批量处理(最动态的优化方式)

提炼每个分支的核心参数,将重复逻辑封装为通用函数,通过配置列表批量执行,彻底消除重复代码:

1. 封装通用处理函数

def populate_data_key(data: dict, group, key: str, filter_like: str, split_suffix: str, nlargest_count: int):
    if key not in data:
        data[key] = []
        # 过滤目标列并统计频次
        filtered_cols = group.filter(like=filter_like)
        # 取Top N项并分割索引值
        for index, _ in filtered_cols.count().nlargest(nlargest_count).items():
            data[key].append(index.split(split_suffix)[1])

2. 定义参数配置列表

把每个分支的关键参数整理成元组列表,后续新增分支仅需添加一行配置:

data_configs = [
    # (data键名, 过滤匹配字符串, 索引分割后缀, 取Top N的数量)
    ("attributes", "attribute", "attribute-", self.nlargest_without_actions),
    ("categories", "category", "category-", self.nlargest_without_actions),
    ("filters", "filters", "filters-", self.nlargest_without_actions),
    ("disliked_products", "dislike-product", "dislike-product-", self.nlargest_with_actions),
    # 后续新增分支直接追加到这里
]

3. 批量执行逻辑

for config in data_configs:
    populate_data_key(data, group, *config)

优势:

  • 新增分支无需修改核心逻辑,仅需补充配置
  • 所有逻辑集中在一处,便于维护和调试
  • 严格遵循DRY(Don't Repeat Yourself)原则

二、OOP策略模式(适合复杂扩展场景)

如果后续不同分支可能出现差异化逻辑(比如去重、排序规则变更),可以用策略模式封装不同处理逻辑,同时通过类管理配置:

1. 定义基础策略与具体实现

from abc import ABC, abstractmethod

class BaseDataPopulator(ABC):
    def __init__(self, key: str, filter_like: str, split_suffix: str, nlargest_count: int):
        self.key = key
        self.filter_like = filter_like
        self.split_suffix = split_suffix
        self.nlargest_count = nlargest_count

    @abstractmethod
    def populate(self, data: dict, group):
        pass

class DefaultPopulator(BaseDataPopulator):
    def populate(self, data: dict, group):
        if self.key not in data:
            data[self.key] = []
            filtered_cols = group.filter(like=self.filter_like)
            for index, _ in filtered_cols.count().nlargest(self.nlargest_count).items():
                data[self.key].append(index.split(self.split_suffix)[1])

# 示例:新增带去重逻辑的策略类
class DeduplicatedPopulator(BaseDataPopulator):
    def populate(self, data: dict, group):
        if self.key not in data:
            data[self.key] = []
            filtered_cols = group.filter(like=self.filter_like)
            seen_values = set()
            for index, _ in filtered_cols.count().nlargest(self.nlargest_count).items():
                value = index.split(self.split_suffix)[1]
                if value not in seen_values:
                    seen_values.add(value)
                    data[self.key].append(value)

2. 初始化策略并执行

populators = [
    DefaultPopulator("attributes", "attribute", "attribute-", self.nlargest_without_actions),
    DefaultPopulator("categories", "category", "category-", self.nlargest_without_actions),
    DefaultPopulator("filters", "filters", "filters-", self.nlargest_without_actions),
    DefaultPopulator("disliked_products", "dislike-product", "dislike-product-", self.nlargest_with_actions),
    # 新增特殊逻辑分支时,使用对应的策略类
    # DeduplicatedPopulator("unique_tags", "tag", "tag-", self.nlargest_without_actions),
]

for populator in populators:
    populator.populate(data, group)

优势:

  • 逻辑隔离,不同分支的处理逻辑互不干扰
  • 扩展性极强,新增逻辑仅需实现新的策略类
  • 代码结构清晰,适合中大型项目长期维护

三、字典映射(适合逻辑差异较大的场景)

如果部分分支的逻辑与其他分支差异明显,可将键名映射到对应的处理函数,兼顾灵活性与可读性:

def handle_basic(data, group, key, filter_str, split_str, n_count):
    if key not in data:
        data[key] = []
        filtered_cols = group.filter(like=filter_str)
        for index, _ in filtered_cols.count().nlargest(n_count).items():
            data[key].append(index.split(split_str)[1])

def handle_disliked_products(data, group):
    # 示例:特殊逻辑分支
    if 'disliked_products' not in data:
        data['disliked_products'] = []
        filtered_cols = group.filter(like='dislike-product')
        # 额外添加自定义逻辑,比如取Top 4后反转顺序
        for index, _ in reversed(list(filtered_cols.count().nlargest(self.nlargest_with_actions).items())):
            data['disliked_products'].append(index.split('dislike-product-')[1])

# 构建处理函数映射
handler_map = {
    'attributes': lambda d, g: handle_basic(d, g, 'attributes', 'attribute', 'attribute-', self.nlargest_without_actions),
    'categories': lambda d, g: handle_basic(d, g, 'categories', 'category', 'category-', self.nlargest_without_actions),
    'filters': lambda d, g: handle_basic(d, g, 'filters', 'filters', 'filters-', self.nlargest_without_actions),
    'disliked_products': handle_disliked_products,
}

# 执行所有处理逻辑
for handler in handler_map.values():
    handler(data, group)

优势:

  • 拆分逻辑清晰,每个函数专注处理特定场景
  • 相同逻辑可复用基础函数,特殊逻辑单独实现
  • 适合混合了通用与特殊逻辑的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:55:29