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

Python Excel多条件判断代码优化:如何替代大量elif语句?

优化你的Excel价格更新脚本

嘿,我完全懂你那种被一堆elif支配的痛苦——重复的判断逻辑不仅看着乱,以后要加新的客户和商品组合时,简直是灾难级的维护工作。咱们用字典映射来重构这段代码,瞬间让它变得简洁、易读还方便扩展!

核心思路

把你需要匹配的「客户ID+商品编码」和对应的价格,整理成一个字典。字典的键可以是(customer_id, article_code)这样的元组,值就是要写入第三列的价格。这样在循环里,我们只需要查字典就能直接拿到对应的值,再也不用写一堆elif了。

优化后的代码

通用版(支持多个客户的规则)

import os
import openpyxl

os.chdir('C:\\Users\\Tadas\\Documents\\Python_pvz')
wb = openpyxl.load_workbook('pardavimai_paprasti.xlsx')
# 注意:openpyxl中get_sheet_by_name已过时,推荐直接用工作表名索引
sheet = wb['Sheet']

# 把所有价格规则整理到字典里,新增规则直接加键值对就行
price_rules = {
    (242061, '0288-0482'): 1,
    (242061, '0288-0757'): 2,
    (242061, '1159-0757'): 3,
    # 以后加新规则直接在这加,比如 (242061, '新编码'): 4
}

for rowNum in range(6, sheet.max_row + 1):  # 这里+1是因为range左闭右开,避免漏最后一行
    customer = sheet.cell(row=rowNum, column=1).value
    article = sheet.cell(row=rowNum, column=2).value
    # 查字典,存在对应规则就写入价格
    price = price_rules.get((customer, article))
    if price is not None:
        sheet.cell(row=rowNum, column=3).value = price

wb.save('updatedpardavimai.xlsx')

简化版(仅针对客户242061)

如果你的所有规则都是针对同一个客户(242061),可以进一步简化字典,只存商品编码和价格的映射,先判断客户再查字典:

import os
import openpyxl

os.chdir('C:\\Users\\Tadas\\Documents\\Python_pvz')
wb = openpyxl.load_workbook('pardavimai_paprasti.xlsx')
sheet = wb['Sheet']

# 只针对客户242061的商品价格映射
customer_242061_prices = {
    '0288-0482': 1,
    '0288-0757': 2,
    '1159-0757': 3,
}

for rowNum in range(6, sheet.max_row + 1):
    customer = sheet.cell(row=rowNum, column=1).value
    article = sheet.cell(row=rowNum, column=2).value
    # 先判断客户,再查商品价格
    if customer == 242061:
        price = customer_242061_prices.get(article)
        if price is not None:
            sheet.cell(row=rowNum, column=3).value = price

wb.save('updatedpardavimai.xlsx')

额外优化点

  • 替换过时方法:get_sheet_by_name在openpyxl的新版本中已经被标记为过时,推荐用wb['Sheet名']的方式获取工作表,更规范。
  • 循环范围修正:原代码的range(6, sheet.max_row)会漏掉最后一行(因为range是左闭右开),改成range(6, sheet.max_row + 1)就能遍历所有需要处理的行。
  • 扩展性提升:以后要加新的价格规则,只需要在字典里添加新的键值对,完全不用修改循环逻辑,维护成本大大降低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:47:00