Python創建二維數組

Python創建二維數組

好不容易查到了建立二維數組的方法,結果我自己array和list真的是傻傻分不清楚,一直以爲自己算法寫錯了,真實的氣死我了。從網上轉載過來一篇博客,引以爲戒,原文地址:
https://www.cnblogs.com/PyLearn/p/7795552.html

1.遇到的問題

今天寫Python代碼的時候遇到了一個大坑,差點就耽誤我交作業了。。。
問題是這樣的,我需要創建一個二維數組,如下:

m = n = 3
test = [[0] * m] * n
print("test =", test)

輸出結果如下:

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

是不是看起來沒有一點問題?
一開始我也是這麼覺得的,以爲是我其他地方用錯了什麼函數,結果這麼一試:

m = n = 3
test = [[0] * m] * n
print("test =", test)

test[0][0] = 233
print("test =", test)

輸出結果如下:

test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
test = [[233, 0, 0], [233, 0, 0], [233, 0, 0]]

是不是很驚訝?!
這個問題真的是折磨我一箇中午,去網上一搜,官方文檔中給出的說明是這樣的:

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也會隨之改變。

2.創建二維數組的辦法

2.1 直接創建法

test = [0, 0, 0], [0, 0, 0], [0, 0, 0]]

簡單粗暴,不過太麻煩,一般不用。

2.2 列表生成式法

test = [[0 for i in range(m)] for j in range(n)]

學會使用列表生成式,終生受益。不會的可以去列表生成式 - 廖雪峯的官方網站學習。

2.3 使用模塊numpy創建

import numpy as np
test = np.zeros((m, n), dtype=np.int)

關於模塊numpy.zeros的更多知識,可以去numpy.zeros(np.zeros)使用方法–python學習筆記31看看。

發佈了10 篇原創文章 · 獲贊 4 · 訪問量 454
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章