2

假设您正在创建一个库存管理系统。

您将获得 2 个字典列表:一个代表我们当前库存中的内容 (l1),另一个代表新装运中的内容 (l2)。

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}]

我们如何将这些列表的数量加在一起,以便我们得到类似的结果:

l3 = [{"product_id": 0, "quantity": 39}, {"product_id": 1, "quantity": 43}, {"product_id": 2, "quantity": 47}]

4

4 回答 4

1

Pandas 可以为此类问题提供一些惊人的解决方案。见下文:

import pandas as pd

df1=pd.DataFrame(l1)
df2=pd.DataFrame(l2)

dfsum=pd.concat([df1, df2]).groupby('product_id').sum().reset_index()

res=dfsum.to_dict(orient='records')

>>> print(res)
[{'product_id': 0, 'quantity': 39}, {'product_id': 1, 'quantity': 43}, {'product_id': 2, 'quantity': 47}]
于 2020-11-28T19:39:44.520 回答
0

第一种情况

L1 和 L2 拥有所有可能的产品

如果 L2 没有产品,则将其插入“0”数量 {“product_id”:10,“数量”:0}

counterOutput = 0

for Element in L1:
  L3[counterOutput]["Product_id]=Element["Product_id"]
  L3[counterOutput]["Quantity"] =Element["Quantity"]+L2[counterOutput]["Quantity"]
  counterOutput ++

第二种情况

L2 可以包含 L1 中不存在的新产品或不同顺序的产品

#Return the quantity of a specific product(0 if product not found)
def SearchProduct(List,ProductId):
    for Element in List:
      if(ProductId == Element["Product_ID"])return Element["QUantity"]
    return 0#not fount

#Search If product exist and sum the old quantity with the new quantity to L3

counterOutput = 0
for Element in L2:
   L3[counterOutput]["Product_ID"]= Element["Product_ID"]
   L3[counterOutput]["Quantity"]= Element["Quantity"] + SearchProduct(L1,Element["Product_ID"])
   counterOutput ++

    
于 2020-11-28T19:42:15.093 回答
0

您可以像这样在一行中使用列表推导来添加:

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}]


result = []
[result.append({"product_id" : i["product_id"], "quantity" : i["quantity"] + j["quantity"]}) for i in l1 for j in l2 if i["product_id"] == j["product_id"]]
print (result)
于 2020-11-28T19:46:28.380 回答
0

有多种方法可以做到这一点,因为您是初学者,所以这必须是最简单的。. . 通过循环从每个字典中获取每个键的值并添加它们

L3 = {}

for i in range(len(l1)):
    # get li and l2 ids
    l1ID = l1[i]['product_id']
    l2ID = l2[i]['product_id']

    # get l1 and l2 qty
    l1Qty = l1[i]['quantity']
    l2Qty = l2[i]['quantity']

    L3[i] = {"id": i, "quantity": int(l1Qty) + int(l2Qty)}

    print(L3)
于 2020-11-28T19:54:34.090 回答