在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

相關文章
相關標籤/搜索