Python: how to create a list of n lists [[],[],[]]

今天做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

發佈了14 篇原創文章 · 獲贊 7 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章