在python中定義二維數組


思維碎片

在python中定義二維數組

一次偶然的機會,發現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 間接定義

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

附:
我的測試代碼

參考:
python的二維數組操作
stackoverflow


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM