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

如何对分析表中paid_ad_impression的valuemicros字符串值求和?

实现paid_ad_impression对应的valuemicros值求和

针对你给出的JSON数据结构,以下是几种实现求和的方法(以Python为例):

基础循环实现

先过滤出event_name为paid_ad_impression的事件,再提取对应的valuemicros字符串并转为整数累加:

# 你的事件数据
events = [{
    "event_name": "paid_ad_impression",
    "event_params": [{
        "key": "valuemicros",
        "value": {
          "string_value": "26072",
          "int_value": None,
          "float_value": None,
          "double_value": None
        }
    }]
}]

total = 0
# 遍历所有事件
for event in events:
    # 筛选目标事件
    if event["event_name"] == "paid_ad_impression":
        # 遍历事件参数找valuemicros
        for param in event["event_params"]:
            if param["key"] == "valuemicros":
                # 转换字符串为整数并累加
                total += int(param["value"]["string_value"])

print(total)  # 输出:26072

简洁的列表推导式实现

用列表推导式简化代码逻辑,直接计算总和:

total = sum(
    int(param["value"]["string_value"])
    for event in events
    if event["event_name"] == "paid_ad_impression"
    for param in event["event_params"]
    if param["key"] == "valuemicros"
)

带异常处理的版本

如果存在string_value无法转为整数的情况,添加异常处理避免程序崩溃:

total = 0
for event in events:
    if event["event_name"] == "paid_ad_impression":
        for param in event["event_params"]:
            if param["key"] == "valuemicros":
                try:
                    total += int(param["value"]["string_value"])
                except ValueError:
                    # 可根据需求调整处理逻辑,比如记录日志或跳过无效值
                    print(f"跳过无效数值:{param['value']['string_value']}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:01:05