Python建立二維數組執行個體(關於list的一個小坑),python二維數組

來源:互聯網
上載者:User

Python建立二維數組執行個體(關於list的一個小坑),python二維數組

0.目錄

1.遇到的問題

2.建立二維數組的辦法

•3.1 直接建立法

•3.2 列表產生式法

•3.3 使用模組numpy建立

1.遇到的問題

今天寫Python代碼的時候遇到了一個大坑,差點就耽誤我交作業了。。。

問題是這樣的,我需要建立一個二維數組,如下:

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

輸出結果如下:

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

是不是看起來沒有一點問題?

一開始我也是這麼覺得的,以為是我其他地方用錯了什麼函數,結果這麼一試:

m = n = 3test = [[0] * m] * nprint("test =", test) test[0][0] = 233print("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 nptest = np.zeros((m, n), dtype=np.int)

關於模組numpy.zeros的更多知識,可以去 python中numpy.zeros(np.zeros)的使用方法 看看。

以上這篇Python建立二維數組執行個體(關於list的一個小坑)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.