[心得] 錯誤的 Multi-dimensinal list 初始化

看板Python作者 (張昱珩)時間12年前 (2013/02/21 01:44), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串1/1
今天犯了一個錯誤,跟大家分享: 初始化一 5 * 5 list 並設初始值為 0 的正確寫法之一是: l = [[0 for i in range(5)] for j in range(5)] 千萬不可以寫成: l = [[0] * 5] * 5 -- UPD 說明如下: -- the beginning of sample code -- a = [[0] * 5] * 5 b = [[0] * 5 for _ in xrange(5)] for i in xrange(5): for j in xrange(5): a[i][j] += 1 b[i][j] += 1 print 'a' for i in xrange(5): print ' '.join(map(str, a[i])) print print 'b' for i in xrange(5): print ' '.join(map(str, b[i])) -- the end of sample code -- -- the beginning of output -- a 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 b 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -- the end of output -- 看起來是因為 a 裡面裝的 5 個 [0, 0, 0, 0, 0] 是一樣的 instance, 會有這樣的結果大概是因為 [[0] * 5] * 5 淺藍色的部分是把黃色的部分的 pointer 複製 4 份 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 36.224.168.156

02/21 02:15, , 1F
裡面寫[0] * 5是可以的 因為0是immutable
02/21 02:15, 1F

02/21 09:01, , 2F
下面多一個右括號
02/21 09:01, 2F
謝謝,已修正 ※ 編輯: changyuheng 來自: 36.224.170.18 (02/21 10:07)
文章代碼(AID): #1H9GkGYL (Python)
文章代碼(AID): #1H9GkGYL (Python)