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

Python二维数组初始化异常求助:修改单元素致多行同步变化

Python二维数组初始化后修改单行影响所有行的原因及解决方法

问题场景

用ary = [[0]*cols]*rows初始化二维数组,调用Insert方法修改ary[0][2]的值后,所有行的第2列都变成了修改后的值,而非仅第0行第2列。

相关代码及输出

初始化代码:

ary = [[0]*cols]*rows

Insert方法:

def Insert(self, val): 
    ary[0][2] = val

打印循环:

for r in range(self.rows):
    for c in range(self.cols):
        self.col = c
        print ('value at row index ', r, ' col index ', c , ' is ',  self.sheet[r][c])

输出结果:

value at row index  0  col index  0  is  0
value at row index  0  col index  1  is  0
value at row index  0  col index  2  is  15
value at row index  0  col index  3  is  20
value at row index  0  col index  4  is  0
value at row index  1  col index  0  is  0
value at row index  1  col index  1  is  0
value at row index  1  col index  2  is  15
value at row index  1  col index  3  is  20
value at row index  1  col index  4  is  0

原因分析

问题出在二维数组的初始化方式,和打印循环无关。

[[0]*cols]*rows的本质是创建了一个包含rows个相同列表对象的数组——数组里的每一行都指向同一个内存地址的列表。当你修改ary[0][2]时,实际上是修改了这个共享的列表元素,所以所有行的对应位置都会同步变化。

解决方法

改用列表推导式初始化二维数组,这样每一行都是独立的新列表:

ary = [[0]*cols for _ in range(rows)]

或者用循环逐行创建:

ary = []
for _ in range(rows):
    ary.append([0]*cols)

这两种方式都会为每一行生成独立的列表对象,修改某一行的元素不会影响其他行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:32:17