Python遍历字典修改列表副本时索引越界错误的修复方法
修复
IndexError: pop index out of range的方案 错误原因
你在正向遍历列表时直接用pop(i)删除元素,会导致列表长度动态缩短:每删一个元素,后续元素会向前移位,原本的索引对应关系失效。比如原列表有3个元素,删了索引0的元素后,列表只剩2个元素,但循环还会走到i=2,自然触发索引越界。
两种可行修复方法
方法1:反向遍历索引(直接修改原列表)
从列表最后一个元素往前遍历,删除操作不会影响前面未遍历的元素索引:
area = [1200, 1200, 1200, 2000] price = [15000, 11000, 17000, 25000] # 假设已生成目标字典 priceDict = {1200: [15000, 11000, 17000], 2000: [25000]} priceIndexDict = {1200: [0, 1, 2], 2000: [3]} for area_val in priceDict: compList = priceDict[area_val] indices = priceIndexDict[area_val] # 计算均值和标准差 mean = sum(compList) / len(compList) std = (sum((x - mean)**2 for x in compList) / len(compList))**0.5 # 反向遍历索引(从最后一位到第0位) for i in range(len(compList)-1, -1, -1): if abs(compList[i] - mean) > 3 * std: compList.pop(i) indices.pop(i)
方法2:生成新列表(更安全,无索引风险)
不修改原列表,直接筛选出非异常值,再更新字典。这种方法避免了索引操作的混乱,代码可读性更高:
area = [1200, 1200, 1200, 2000] price = [15000, 11000, 17000, 25000] # 假设已生成目标字典 priceDict = {1200: [15000, 11000, 17000], 2000: [25000]} priceIndexDict = {1200: [0, 1, 2], 2000: [3]} for area_val in priceDict: compList = priceDict[area_val] indices = priceIndexDict[area_val] # 计算均值和标准差 mean = sum(compList) / len(compList) std = (sum((x - mean)**2 for x in compList) / len(compList))**0.5 # 筛选非异常值,同时保留对应索引 filtered_pairs = [(p, idx) for p, idx in zip(compList, indices) if abs(p - mean) <= 3 * std] # 更新字典 priceDict[area_val] = [p for p, idx in filtered_pairs] priceIndexDict[area_val] = [idx for p, idx in filtered_pairs]
额外提示
如果你的数据量较大,建议用numpy计算均值和标准差,效率更高:
import numpy as np mean = np.mean(compList) std = np.std(compList)
内容的提问来源于stack exchange,提问作者YuanLinTech
相关产品推荐
相关产品推荐

