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

Python多维列表元素交换失效问题排查及解决

多维列表修改失效问题的解决方案

问题核心

你的代码在嵌套列表场景下失效,根源是浅拷贝导致副本与原列表共享子列表内存,同时存在空元素位置未动态更新、副本重置方式错误的问题:

  • current_loc.copy()是浅拷贝,仅复制外层列表的引用,内部子列表仍和原列表指向同一内存空间,修改副本里的子列表元素会直接改动原列表。
  • 初始仅查找一次空元素位置empty,但每次移动后空位置会变化,后续移动会使用错误索引。
  • 循环内重置temp时仍用浅拷贝,无法生成独立的全新列表。

修复方案

  1. 深拷贝创建独立副本:用列表推导式逐个复制子列表,或copy.deepcopy(),确保副本与原列表完全隔离。
  2. 每次移动前重新生成副本:每个移动指令都基于原列表创建全新副本,避免之前的修改影响后续操作。
  3. 动态查找空元素位置:每次移动后重新定位空元素的索引,保证操作位置正确。

修改后的完整代码

curpos = [[88, 118, 1], [200, 118, 0], [312, 118, 2],
          [88, 230, 3], [200, 230, 4], [312, 230, 5],
          [88, 342, 6], [200, 342, 7], [312, 342, 8]]
movls = ['right', 'down', 'left']

def move_tile(current_loc, movlist):
    result = []
    for j in movlist:
        # 深拷贝原列表,生成完全独立的嵌套列表副本
        temp = [sub.copy() for sub in current_loc]
        # 查找当前空元素的位置
        empty = None
        for idx, item in enumerate(temp):
            if item[2] == 0:
                empty = idx
                break
        # 执行对应移动操作
        if j == 'right':
            temp[empty][2] = temp[empty+1][2]
            temp[empty+1][2] = 0 
        elif j == 'down':
            temp[empty][2] = temp[empty+3][2]
            temp[empty+3][2] = 0
        elif j == 'left':
            temp[empty][2] = temp[empty-1][2]
            temp[empty-1][2] = 0
        elif j == 'up':
            temp[empty][2] = temp[empty-3][2]
            temp[empty-3][2] = 0
        # 将当前移动后的状态加入结果列表
        result.append(temp)
    return result

# 输出结果
print(move_tile(curpos, movls))

期望输出

运行后将得到你需要的结果:

[[[88, 118, 1], [200, 118, 2], [312, 118, 0],
  [88, 230, 3], [200, 230, 4], [312, 230, 5],
  [88, 342, 6], [200, 342, 7], [312, 342, 8]],

 [[88, 118, 1], [200, 118, 4], [312, 118, 2],
  [88, 230, 3], [200, 230, 0], [312, 230, 5],
  [88, 342, 6], [200, 342, 7], [312, 342, 8]],

 [[88, 118, 0], [200, 118, 1], [312, 118, 2],
  [88, 230, 3], [200, 230, 4], [312, 230, 5],
  [88, 342, 6], [200, 342, 7], [312, 342, 8]]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:10:22