Problem creating N*N*N list in Python

天大地大妈咪最大 提交于 2019-12-24 04:09:48

问题


I'm trying to create a 3-dimensional NNN list in Python, like such:

n=3
l = [[[0,]*n]*n]*n

Unfortunately, this does not seem to properly "clone" the list, as I thought it would:

>>> l
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> l[0][0][0]=1
>>> l
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]

What am I doing wrong here?


回答1:


The problem is that * n does a shallow copy of the list. A solution is to use nested loops, or try the numpy library.




回答2:


If you want to do numerical processing with 3-d matrix you are better of using numpy. It is quite easy:

>>> import numpy
>>> numpy.zeros((3,3,3), dtype=numpy.int)
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]])
>>> _[0,0,0]
0



回答3:


As others have mentioned, it's building the 2nd and 3rd levels with references, not clones. Try:

>>> n = 3

>>> l = [[[0]*n for _ in xrange(n)] for _ in xrange(n)]

>>> l[0][0][0] = 1

>>> l
[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]

Or if you want to type a bit less:

>>> l = [[[0]*n for _ in '.'*n] for _ in '.'*n]



回答4:


It's not cloning the list. It's inserting a reference to the same list over and over. Try creating the list using a set of nested for loops.




回答5:


I have to second what leonardo-santagada suggested, with the addition that creating N dimensional arrays/lists is very unpythonic and you should reconsider how you're keeping your data and seeing if it doesn't belong better in a class or a list of dictionaries (or dictionaries of lists).



来源:https://stackoverflow.com/questions/1889080/problem-creating-nnn-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!