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

Python列表筛选排序重复代码的重构优化建议

代码重构方案

原代码存在两处明显的逻辑重复:

  • 两次遍历plans列表做成员判断拆分数据,数据量大时会产生不必要的性能开销
  • 两次调用sorted时传入了完全相同的排序规则,重复编写了相同参数

你可以根据后续是否需要复用拆分后的两个子列表,选择对应的重构方式:


方案1:最精简实现(无需复用子列表时用)

根本不需要提前拆分列表+两次排序+拼接,直接通过自定义排序key,单次排序就能实现完全一致的效果,零重复逻辑:

# 把id列表转为集合,成员判断时间复杂度从O(n)降到O(1),性能更好
plans_ids_with_attribute = {3024, 3045, 3060}

sorted_plans = sorted(
    plans,
    # 排序优先级:先按「是否属于带属性计划」升序(False=0 < True=1,无属性计划自然排前面),再按权重倒序
    key=lambda p: (p.id in plans_ids_with_attribute, -p.weight)
)

实现逻辑和原代码完全等价:无属性的计划全部排在带属性的计划之前,两组内部都按权重从高到低排序。如果觉得-p.weight的写法可读性差,也可以把key写成lambda p: (0 if p.id not in plans_ids_with_attribute else 1, p.weight),搭配reverse=True实现相同效果。


方案2:保留拆分逻辑(需要复用子列表时用)

如果后续逻辑还要单独使用拆分后的plans_with_attribute、plans_without_attribute两个列表,就做两处优化消除重复:

  1. 把两次列表推导的遍历合并成一次,单次循环完成拆分
  2. 把重复的按权重倒序逻辑抽成公共函数,避免重复写排序参数
plans_ids_with_attribute = {3024, 3045, 3060}
plans_with_attribute = []
plans_without_attribute = []

# 单次遍历完成拆分
for plan in plans:
    if plan.id in plans_ids_with_attribute:
        plans_with_attribute.append(plan)
    else:
        plans_without_attribute.append(plan)

# 抽离公共排序规则
def sort_by_weight_desc(plan_group):
    return sorted(plan_group, key=lambda p: p.weight, reverse=True)

sorted_plans = sort_by_weight_desc(plans_without_attribute) + sort_by_weight_desc(plans_with_attribute)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 07:33:16