Python的二维数组初始化

 Python一维数组初始化

In [1]: a = [0]*5

In [2]: a
Out[2]: [0, 0, 0, 0, 0]

In [3]: a[1]=1

In [4]: a
Out[4]: [0, 1, 0, 0, 0]

     

Python的一维数组初始化时没有太大问题,但是二维初始化就不能这么搞了,不信你看



In [5]: a = [[0]*5]*5

In [6]: a
Out[6]:
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

In [7]: a[1][1] = 1

In [8]: a
Out[8]:
[[0, 1, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 1, 0, 0, 0]]

这样初始化实际上是相当于浅拷贝,只拷贝了个索引。

应该用列表生成器来初始化二维数组

In [12]: b = [[0]*5 for _ in range(5)]

In [13]: b
Out[13]:
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

In [14]: b[3][3] = 3

In [15]: b
Out[15]:
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 3, 0],
 [0, 0, 0, 0, 0]]

猜你喜欢

转载自blog.csdn.net/sinat_21791203/article/details/108348466