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

如何遍历包含None类型的嵌套数组并跳过None元素

解决TypeError: 'NoneType' object is unsubscriptable问题

你遇到的错误是因为当element为None时,尝试执行element[0]——None不支持下标访问。要跳过这些空元素,只需在访问下标前先判断元素是否为None即可。

修复后的代码

field = [ [['PEASH', 5], None, None, None, None, None, ['ZOMB', 15]],
          [['PEASH', 5], None, None, None, None, None, ['ZOMB', 15]],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None],
          [None, None, None, None, None, None, None] ]

num_rows=len(field)
num_columns=len(field[0])

lane = 0
row_counter = -1
column_counter = -1
for row in range(num_rows):
    row_counter += 1
    print('rowcounter is at',row_counter)
    print(row)
    column_counter = -1  # 重置列计数器,避免跨行列计数累加错误
    for column in range(num_columns):
        column_counter += 1

        element = field[row][column] 
        print(element)
        # 先判断元素不为None,再检查类型
        if element is not None and element[0] == 'PEASH':
            print('yes there is a peashooter in',row_counter,column_counter)

核心修改说明

  • 跳过None元素:增加element is not None的判断,确保只有非空元素才会执行下标访问,直接避免TypeError。
  • 可选写法:也可以用continue直接跳过空元素,逻辑更清晰:
    element = field[row][column] 
    print(element)
    if element is None:
        continue  # 跳过当前列,直接进入下一列循环
    if element[0] == 'PEASH':
        print('yes there is a peashooter in',row_counter,column_counter)
    
  • 额外优化:原代码中column_counter会在所有行中持续累加,导致列计数混乱。把column_counter = -1放到外层循环(每行开始时),可以让每行列计数从0重新开始。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:03:46