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
相关产品推荐
相关产品推荐

