在python中定义二维数组

 

发表于 http://liamchzh.0fees.net/?p=234&i=1

一次偶然的机会,发现python中list很是有意思。html

先看一段代码python

[py]
array = [0, 0, 0]
matrix = [array*3]
print matrix
## [[0,0,0,0,0,0,0,0,0]][/py]git

这段代码其实没有新建一个二维数组github

再看一段代码数组

[py]
array = [0, 0, 0]
matrix = [array] * 3
print matrix
## [[0, 0, 0], [0, 0, 0], [0, 0, 0]][/py]app

咋一看这段代码应该建立一个二维数组了ide

测试一下测试

[py]
matrix[0][1] = 1
print matrix
## [[0, 1, 0], [0, 1, 0], [0, 1, 0]][/py]this

照理matrix[0][1]修改的应该只是二维数组中的一个元素,可是测试结果代表,修改的是每一个List的第二个元素。
有问题看文档,而后我找到了The Python Standard Library
其中5.6. Sequence Types是这样描述的:spa

Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>>
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
也就是说matrix = [array] * 3操做中,只是建立3个指向array的引用,因此一旦array改变,matrix中3个list也会随之改变。

那如何才能在python中建立一个二维数组呢?
例如建立一个3*3的数组
方法1 直接定义

[py]matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]][/py]

方法2 间接定义

matrix = [[0 for i in range(3)] for i in range(3)]

附:
个人测试代码

参考:
python的二维数组操做
stackoverflow

相关文章
相关标签/搜索