今天做leetcode螺旋寫入矩陣https://leetcode.com/problems/spiral-matrix-ii/ 這個題目的時候,需要初始化一個含有n個list的list,因爲對python不是特別的熟悉,剛開始用的初始化寫法是:
a = [[0]*n]*n
這就生成了一個n行n列的list,但是給列表賦值的時候會發生錯誤,比如n=3, a[0][1]=2 那鏈表則變成了a = [[0,2,0],[0,2,0],[0,2,0]]
解釋:
The problem is that they’re all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they’re all references to the same object. They’re not distinct instances, rather, just n references to the same instance.
make a list of 3 different lists, do this:
x = [[] for i in range(3)]
因此上面的初始化應該寫成:
a = [[0]*n for x in range(n)]
詳細解釋見:http://stackoverflow.com/questions/12791501/python-initializing-a-list-of-lists