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

编写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_idproduct_idpriceorder_delivery_costnew_column
987471832160092.95
9874719654600189.38
9874720987600285.81
987472511060031.85

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:12:58