Python向嵌套列表追加数据失败,触发IndexError下标越界错误
报错原因
sumList初始化时是空列表,没有预创建嵌套的子列表元素。第一层循环首次执行i=0时,直接访问sumList[i]等同于访问空列表的第0位元素,不存在对应索引,因此触发IndexError: list index out of range错误。
解决方案
提供两种可直接运行的修复方案:
- 方案1:在原有循环逻辑基础上补充子列表初始化操作
distList = [[0.0, 0.0, 0.0, 0.0, 0.0], [-1.76333, -4.22504, -2.42978, 0.81744, 0.1], [-0.91351, -3.76965, -3.34161, -1.66984, 0.1], [-2.5362, 0.22098, -3.49264, -2.34982, 0.1]] sumList = [] for i in range(len(distList)): # 先为当前i索引创建空的子列表,再执行追加操作 sumList.append([]) for j in range(len(distList[i])): sumofNum = distList[i][j] * distList[i][j] sumList[i].append(sumofNum)
- 方案2:使用列表推导式简化实现,避免手动处理索引
distList = [[0.0, 0.0, 0.0, 0.0, 0.0], [-1.76333, -4.22504, -2.42978, 0.81744, 0.1], [-0.91351, -3.76965, -3.34161, -1.66984, 0.1], [-2.5362, 0.22098, -3.49264, -2.34982, 0.1]] sumList = [[num ** 2 for num in sub_list] for sub_list in distList]
内容的提问来源于stack exchange,提问作者Reetu Gujjar
相关产品推荐
相关产品推荐

