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

2017-01-13 11:34:14来源:CSDN作者:wanghai00人点击

第七城市

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

第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台