Problem creating N*N*N list in Python

2019-07-23 10:03发布

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?

5条回答
该账号已被封号
2楼-- · 2019-07-23 10:10

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

查看更多
时光不老,我们不散
3楼-- · 2019-07-23 10:10

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楼-- · 2019-07-23 10:11

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
查看更多
Summer. ? 凉城
5楼-- · 2019-07-23 10:22

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.

查看更多
虎瘦雄心在
6楼-- · 2019-07-23 10:29

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).

查看更多
登录 后发表回答