Python創(chuàng)建二維數(shù)組實例(關(guān)于list的一個小坑)
0.目錄
1.遇到的問題
2.創(chuàng)建二維數(shù)組的辦法
•3.1 直接創(chuàng)建法
•3.2 列表生成式法
•3.3 使用模塊numpy創(chuàng)建
1.遇到的問題
今天寫Python代碼的時候遇到了一個大坑,差點(diǎn)就耽誤我交作業(yè)了。。。
問題是這樣的,我需要創(chuàng)建一個二維數(shù)組,如下:
m = n = 3
test = [[0] * m] * n
print("test =", test)
輸出結(jié)果如下:
test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
是不是看起來沒有一點(diǎn)問題?
一開始我也是這么覺得的,以為是我其他地方用錯了什么函數(shù),結(jié)果這么一試:
m = n = 3
test = [[0] * m] * n
print("test =", test)
test[0][0] = 233
print("test =", test)
輸出結(jié)果如下:
test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] test = [[233, 0, 0], [233, 0, 0], [233, 0, 0]]
是不是很驚訝?!
這個問題真的是折磨我一個中午,去網(wǎng)上一搜,官方文檔中給出的說明是這樣的:
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操作中,只是創(chuàng)建3個指向array的引用,所以一旦array改變,matrix中3個list也會隨之改變。
2.創(chuàng)建二維數(shù)組的辦法
2.1 直接創(chuàng)建法
test = [0, 0, 0], [0, 0, 0], [0, 0, 0]]
簡單粗暴,不過太麻煩,一般不用。
2.2 列表生成式法
test = [[0 for i in range(m)] for j in range(n)]
學(xué)會使用列表生成式,終生受益。不會的可以去列表生成式 - 廖雪峰的官方網(wǎng)站學(xué)習(xí)。
2.3 使用模塊numpy創(chuàng)建
import numpy as np test = np.zeros((m, n), dtype=np.int)
關(guān)于模塊numpy.zeros的更多知識,可以去 python中numpy.zeros(np.zeros)的使用方法 看看。
以上這篇Python創(chuàng)建二維數(shù)組實例(關(guān)于list的一個小坑)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
我對PyTorch dataloader里的shuffle=True的理解
這篇文章主要介紹了我對PyTorch dataloader里的shuffle=True的理解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
python os.path.isfile 的使用誤區(qū)詳解
今天小編就為大家分享一篇python os.path.isfile 的使用誤區(qū)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
吳恩達(dá)機(jī)器學(xué)習(xí)練習(xí):SVM支持向量機(jī)
這篇文章主要為我們帶來了吳恩達(dá)機(jī)器學(xué)習(xí)的一個練習(xí):SVM支持向量機(jī),通過本次練習(xí)相信你能對機(jī)器學(xué)習(xí)深入更進(jìn)一步,需要的朋友可以參考下2021-04-04
Python?虛擬環(huán)境遷移到其他電腦的實現(xiàn)
本文主要介紹了Python?虛擬環(huán)境遷移到其他電腦的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04

