[心得] 錯誤的 Multi-dimensinal list 初始化
今天犯了一個錯誤,跟大家分享:
初始化一 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
02/21 02:15, 1F
推
02/21 09:01, , 2F
02/21 09:01, 2F
謝謝,已修正
※ 編輯: changyuheng 來自: 36.224.170.18 (02/21 10:07)
Python 近期熱門文章
PTT數位生活區 即時熱門文章