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

Python追加嵌套列表到主列表时内容无法正确保留问题求助

问题原因

Python中列表是可变对象,代码中end_point始终指向同一个列表内存地址,你每次将它添加到point_logs时,存入的只是这个内存地址的引用,而非当前点位的独立副本。后续修改end_point的元素值时,所有指向该地址的引用都会同步更新,所以最终所有日志记录都会变成最后一次修改后的终点值。

解决方案

每次向日志中添加点位时,拷贝当前end_point的独立副本即可,可选的拷贝方式:

  • 切片拷贝:end_point[:]
  • 构造新列表:list(end_point)
  • 调用copy方法:end_point.copy()

修正后的代码

matrix = [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]

def position(inital_point,*steps):
    end_point = inital_point
    point_logs = []
    # 存入初始点位的副本
    point_logs.append(end_point[:])
    for step in steps:
        end_point[0] += step[0]
        end_point[1] += step[1]
        # 每次存入当前点位的副本
        point_logs.append(end_point[:])
    print(point_logs)
        
position([1,1],[1,1],[1,1])

运行输出:

[[1, 1], [2, 2], [3, 3]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:48:03