编写Python函数为字典列表添加按product_id价格加权的配送成本列
为字典列表添加加权配送成本列的Python实现
给定如下字典列表:
q = [ {"order_id": 987, "product_id": 4718, "price": 321, "order_delivery_cost": 600}, {"order_id": 987, "product_id": 4719, "price": 654, "order_delivery_cost": 600}, {"order_id": 987, "product_id": 4720, "price": 987, "order_delivery_cost": 600}, {"order_id": 987, "product_id": 4725, "price": 110, "order_delivery_cost": 600} ]
需求是给每个字典新增new_column字段,值为以对应price为权重的order_delivery_cost加权值,计算逻辑为:new_column = (当前产品price / 该订单总price) * order_delivery_cost,结果保留两位小数。
实现代码
def add_weighted_delivery_cost(data): # 计算当前订单的总价格(此处所有数据属于同一order_id,直接求和即可) total_price = sum(item["price"] for item in data) # 遍历每个字典,添加加权成本字段 for item in data: weighted_cost = (item["price"] / total_price) * item["order_delivery_cost"] item["new_column"] = round(weighted_cost, 2) return data # 调用函数处理数据 result = add_weighted_delivery_cost(q)
最终结果
处理后的数据对应表格如下:
| order_id | product_id | price | order_delivery_cost | new_column |
|---|---|---|---|---|
| 987 | 4718 | 321 | 600 | 92.95 |
| 987 | 4719 | 654 | 600 | 189.38 |
| 987 | 4720 | 987 | 600 | 285.81 |
| 987 | 4725 | 110 | 600 | 31.85 |
内容的提问来源于stack exchange,提问作者LJ_
相关产品推荐
相关产品推荐

