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

如何用Python从API返回的JSON中提取首个时间点的temperature_2m值?

从API返回的JSON中提取首个时间点对应的温度值

你要提取JSON里首个时间点2022-11-03T00:00对应的temperature_2m值,但现有代码存在两个关键问题:

  • 遍历api_query所有key的循环完全多余,和提取目标值没有关联
  • api_query['hourly']['time'][0]是字符串类型的时间值,并非字典,不能用['temperature_2m']去访问它

方法一:直接按索引提取(推荐)

因为hourly下的time和temperature_2m列表是严格一一对应的,首个时间对应的就是温度列表的第一个元素,直接取索引0即可:

api_query ={
    "latitude": 52.52,
    "longitude": 13.419998,
    "generationtime_ms": 0.36203861236572266,
    "utc_offset_seconds": 0,
    "timezone": "GMT",
    "timezone_abbreviation": "GMT",
    "elevation": 38.0,
    "hourly_units": {
        "time": "iso8601",
        "temperature_2m": "°C"
    },
    "hourly": {
        "time": [
            "2022-11-03T00:00",
            "2022-11-03T01:00"
           
        ],
        "temperature_2m": [
            5.7,
            5.2
           
        ]
    }
}

# 提取首个时间对应的温度
first_temperature = api_query['hourly']['temperature_2m'][0]
print(first_temperature)  # 输出5.7

方法二:按指定时间值查找(适用于不确定目标时间位置的场景)

如果需要通过具体时间字符串匹配对应的温度,可以先获取该时间在time列表中的索引,再用索引提取温度:

api_query ={
    "latitude": 52.52,
    "longitude": 13.419998,
    "generationtime_ms": 0.36203861236572266,
    "utc_offset_seconds": 0,
    "timezone": "GMT",
    "timezone_abbreviation": "GMT",
    "elevation": 38.0,
    "hourly_units": {
        "time": "iso8601",
        "temperature_2m": "°C"
    },
    "hourly": {
        "time": [
            "2022-11-03T00:00",
            "2022-11-03T01:00"
           
        ],
        "temperature_2m": [
            5.7,
            5.2
           
        ]
    }
}

target_time = "2022-11-03T00:00"
time_list = api_query['hourly']['time']
temp_list = api_query['hourly']['temperature_2m']

if target_time in time_list:
    index = time_list.index(target_time)
    target_temperature = temp_list[index]
    print(target_temperature)  # 输出5.7
else:
    print("目标时间不存在于数据中")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:40:28