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

库存管理系统中如何合并两个字典列表的产品库存数量

合并库存列表:按product_id累加quantity

嘿,这个库存合并的需求很典型,我来给你分享几种实用的实现思路,其中最推荐的是用字典做快速映射的方法,效率高还容易维护:

方法一:字典映射法(推荐)

这种方法利用字典的O(1)查找/更新特性,处理数据的效率非常高,哪怕是大规模库存数据也能轻松应对。步骤如下:

  1. 先把当前库存列表l1转换成以product_id为键、quantity为值的字典,方便快速定位商品;
  2. 遍历新到货库存l2,对每个商品的数量进行累加;
  3. 最后把字典转回要求的列表格式,如果需要保持product_id的顺序,再做一次排序即可。

对应的Python代码:

l1 = [{"product_id": 0, "quantity": 9}, {"product_id": 1, "quantity": 18}, {"product_id": 2, "quantity": 22}]
l2 = [{"product_id": 0, "quantity": 30}, {"product_id": 1, "quantity": 25}, {"product_id": 2, "quantity": 25}]

# 1. 转换l1为字典
inventory_map = {item["product_id"]: item["quantity"] for item in l1}

# 2. 累加l2的库存
for item in l2:
    pid = item["product_id"]
    # 如果是题目中这种l1和l2商品完全匹配的情况,也可以直接省略判断
    if pid in inventory_map:
        inventory_map[pid] += item["quantity"]
    else:
        # 额外处理:如果l2有l1没有的新商品,直接添加到字典中
        inventory_map[pid] = item["quantity"]

# 3. 转换回目标列表格式并排序(保证product_id顺序和示例一致)
l3 = [{"product_id": pid, "quantity": qty} for pid, qty in sorted(inventory_map.items())]

print(l3)
# 输出:[{"product_id": 0, "quantity": 39}, {"product_id": 1, "quantity": 43}, {"product_id": 2, "quantity": 47}]

方法二:简化版(已知商品完全匹配)

如果能确定l1和l2的product_id完全一一对应(就像题目给出的示例数据),可以省略存在性判断,代码会更简洁:

inventory_map = {item["product_id"]: item["quantity"] for item in l1}
for item in l2:
    inventory_map[item["product_id"]] += item["quantity"]
l3 = [{"product_id": pid, "quantity": qty} for pid, qty in sorted(inventory_map.items())]

不推荐的方法:双重循环遍历

虽然可以用双重循环逐个匹配product_id再累加,但这种方法的时间复杂度是O(n²),当库存商品数量较多时,性能会很差,所以不建议使用:

l3 = []
# 先复制l1的内容作为基础
for item in l1:
    l3.append(item.copy())
# 遍历l2,逐个匹配累加
for new_item in l2:
    for existing_item in l3:
        if existing_item["product_id"] == new_item["product_id"]:
            existing_item["quantity"] += new_item["quantity"]
            break

总结下来,字典映射法是最优解,既高效又灵活,还能处理新增商品的场景~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:35:41