使用for循环与enumerate操作嵌套列表元素的问题求助
问题解决:嵌套列表指定位置元素加值
需求回顾
要修改嵌套列表,仅对第2到第5个嵌套列表(对应Python索引1到4)中,排除首尾元素后的第2、3位(对应子列表索引2、3)的元素加1。
你的代码问题分析
第一次尝试的问题:
range(1,-1)是无效范围,步长默认正,不会生成任何循环值,直接跳过循环enumerate(List, start=1)遍历的是外层列表的子列表,item是整个子列表,不是单个元素,item > 1判断毫无意义List[index] = ...是把外层列表的子列表替换成数字,完全不符合需求
第二次尝试的问题:
example_list[j] = round((example_list[j]+x),3)这里example_list[j]是嵌套列表,加整数x会触发类型错误(列表不能和整数拼接)- 嵌套循环的索引逻辑混乱,
enumerate(sub_list[1:-1][1:-1], start=2)生成的j和实际子列表的索引对应关系出错,导致修改位置不对
正确解决方案
方案1:处理含nan的原列表
导入math模块判断nan(避免对nan做无效操作),精准遍历目标索引:
import math original_list = [ [math.nan, 4, 5, math.nan, math.nan, math.nan, math.nan], [math.nan, 4, 2, 3, 5, math.nan, math.nan], [math.nan, 4, 2, 3, 5, math.nan, math.nan], [math.nan, 4, 2, 3, 5, math.nan, math.nan], [math.nan, 4, 2, 3, 5, math.nan, math.nan], [math.nan, 4, 5, math.nan, math.nan, math.nan, math.nan] ] # 遍历第2到第5个嵌套列表(索引1到4) for sub_list in original_list[1:5]: # 对每个子列表的索引2、3位置元素加1 for idx in [2, 3]: if not math.isnan(sub_list[idx]): sub_list[idx] += 1 # 打印结果 for row in original_list: print(row)
方案2:处理用0替代nan的列表
逻辑更简洁,无需判断nan:
example_list = [ [0, 4, 5, 0, 0, 0, 0], [0, 4, 2, 3, 5, 0, 0], [0, 4, 2, 3, 5, 0, 0], [0, 4, 2, 3, 5, 0, 0], [0, 4, 2, 3, 5, 0, 0], [0, 4, 5, 0, 0, 0, 0] ] # 遍历目标子列表(索引1到4) for sub_list in example_list[1:-1]: # 直接修改索引2、3的元素 sub_list[2] += 1 sub_list[3] += 1 # 打印结果 for row in example_list: print(row)
结果验证
运行后会得到你预期的效果:
- 第1和第6个嵌套列表保持不变
- 中间4个嵌套列表的索引2、3位置元素(原2和3)都变成3和4
内容的提问来源于stack exchange,提问作者Patstro
相关产品推荐
相关产品推荐

