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

如何在多层嵌套数组中将指定子数组左移一位并替换原位置为None

实现三层嵌套数组的内层子数组左移操作

你需要将三层嵌套数组中每一行的非None最内层子数组,向左移动一位到相邻的None位置,原位置替换为None,所有符合条件的行都执行此操作。

以你给出的示例数组为例,处理后的结果应为:

[
    [['PEASH', 5], None, None, None, None, ['ZOMB', 15], None],
    [['PEASH', 5], 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, 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] ]

# 遍历每一行处理
for row in field:
    # 从右往左遍历元素索引,避免左移操作干扰后续判断
    for i in range(len(row)-1, 0, -1):
        if row[i] is not None and row[i-1] is None:
            row[i-1] = row[i]
            row[i] = None

# 输出验证结果
for line in field:
    print(line)

代码说明

  • 外层循环遍历数组中的每一行,针对每行单独处理
  • 内层循环从右往左遍历行内元素的索引:如果从左往右遍历,左边元素左移后会覆盖右侧的None,导致后续元素无法正确移动,反向遍历可以避免这个问题
  • 当检测到当前元素非None且左侧相邻位置是None时,将当前元素移动到左侧位置,同时把原位置设为None

内容的提问来源于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:39:24