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

如何改写重复的Python字典值处理代码以消除冗余?

代码优化方案:消除重复逻辑

核心思路

把原代码里重复的数值提取、文本后缀提取、字典更新逻辑抽出来,只根据操作类型(加减)处理核心运算,砍掉冗余代码,让后续维护更方便。

优化后的代码

import re

def modify_inventory(inventory_list, key, quantity, modify_options):
    # 取出字典中对应键的原始内容
    item_content = inventory_list[key]
    
    # 提取浮点数部分(匹配整数或小数格式)
    num_match = re.search(r"\d+\.?\d*", item_content)
    current_quantity = float(num_match.group())
    
    # 提取文本描述部分(移除数字、点、冒号后清理多余空格)
    item_desc = re.sub(r"[\d.:]+", "", item_content).strip()
    
    # 根据操作类型计算新数值
    if modify_options == "1":
        new_quantity = current_quantity + quantity
    elif modify_options == "2":
        new_quantity = current_quantity - quantity
    else:
        # 遇到无效操作时直接返回原字典
        return inventory_list
    
    # 重新拼接内容并更新字典
    inventory_list[key] = f"{new_quantity} {item_desc}"
    return inventory_list

优化细节说明

  1. 复用提取逻辑:原代码里两次重复的正则提取操作合并成一次,避免做无用的重复计算。
  2. 正则表达式优化:
    • 用re.search替代re.findall,直接拿到第一个匹配的数值,比返回列表再取索引更高效。
    • 替换原有的纯字母匹配逻辑,改用re.sub移除数字、点和冒号,能准确提取示例里的"chicken"文本(适配原数据里的冒号和空格)。
  3. 统一更新逻辑:拼接字符串和更新字典的操作只写一次,后续要改格式只需要调整这一处。
  4. 增加容错处理:对无效的modify_options值做了默认处理,避免程序直接报错。

使用示例

# 测试用例
inventory = {"food": "19.0: chicken"}
# 执行加法操作(操作类型1,增量3)
updated_inventory = modify_inventory(inventory, "food", 3, "1")
print(updated_inventory["food"])  # 输出: 22.0 chicken

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 06:31:06