Create 3D array using Python

前端 未结 9 1117
情话喂你
情话喂你 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]]]
    
    0 讨论(0)
  • 2020-12-23 10:29

    The right way would be

    [[[0 for _ in range(n)] for _ in range(n)] for _ in range(n)]
    

    (What you're trying to do should be written like (for NxNxN)

    [[[0]*n]*n]*n
    

    but that is not correct, see @Adaman comment why).

    0 讨论(0)
  • 2020-12-23 10:29
    def n_arr(n, default=0, size=1):
        if n is 0:
            return default
    
        return [n_arr(n-1, default, size) for _ in range(size)]
    
    arr = n_arr(3, 42, 3)
    assert arr[2][2][2], 42
    
    0 讨论(0)
提交回复
热议问题