一次偶然的机会,发现python中list非常有意思。
先看一段代码
[py]
array = [0, 0, 0]
matrix = [array*3]
print matrix
## [[0,0,0,0,0,0,0,0,0]][/py]
这段代码其实没有新建一个二维数组
再看一段代码
[py]
array = [0, 0, 0]
matrix = [array] * 3
print matrix
## [[0, 0, 0], [0, 0, 0], [0, 0, 0]][/py]
咋一看这段代码应该创建一个二维数组了
测试一下
[py]
matrix[0][1] = 1
print matrix
## [[0, 1, 0], [0, 1, 0], [0, 1, 0]][/py]
照理matrix[0][1]修改的应该只是二维数组中的一个元素,但是测试结果表明,修改的是每个List的第二个元素。
有问题看文档,然后我找到了The Python Standard Library
其中5.6. Sequence Types是这样描述的:
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)]
附:
我的测试代码