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

Python函数生成带递增键字典仅取列表首值问题求助

错误原因
  • 遍历逻辑错误:当前代码的循环遍历对象是(temp, rain, humidity, wind)四个列表本身,循环仅会执行4次,和列表内部的元素数量无关,不符合按位置匹配四个参数的需求。
  • 取值逻辑错误:每次给字典赋值时,没有按索引取四个列表对应位置的元素,直接传入了完整列表,无法得到预期的逐组参数组合。
修正后代码
def create_db(temp, rain, humidity, wind):
    # 校验四个参数列表长度一致
    if len(temp) != len(rain) or len(temp) != len(humidity) or len(temp) != len(wind):
        raise ValueError("四个输入列表的长度必须相等")
    weather = {}
    # 遍历列表索引,按键从1开始生成键值对
    for idx in range(len(temp)):
        weather[idx + 1] = (temp[idx], rain[idx], humidity[idx], wind[idx])
    return weather

temp = [1, 5, 3]
rain = [0, 30, 100]
humidity = [30, 50, 65]
wind = [3, 5, 7]
weather = create_db(temp, rain, humidity, wind)
print(weather)
运行结果
{1: (1, 0, 30, 3), 2: (5, 30, 50, 5), 3: (3, 100, 65, 7)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:45:05