Create 3D array using Python

前端 未结 9 1167
情话喂你
情话喂你 2020-12-23 09:57

I would like to create a 3D array in Python (2.7) to use like this:

distance[i][j][k]

And the sizes of the array should be the size of a vari

9条回答
  •  执念已碎
    2020-12-23 10:18

    You should use a list comprehension:

    >>> import pprint
    >>> n = 3
    >>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
    >>> pprint.pprint(distance)
    [[[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]]]
    >>> distance[0][1]
    [0, 0, 0]
    >>> distance[0][1][2]
    0
    

    You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:

    >>> distance=[[[0]*n]*n]*n
    >>> pprint.pprint(distance)
    [[[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]]]
    >>> distance[0][0][0] = 1
    >>> pprint.pprint(distance)
    [[[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]]]
    

提交回复
热议问题