Create 3D array using Python

前端 未结 9 1199
情话喂你
情话喂你 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:10

    """
    Create 3D array for given dimensions - (x, y, z)
    
    @author: Naimish Agarwal
    """
    
    
    def three_d_array(value, *dim):
        """
        Create 3D-array
        :param dim: a tuple of dimensions - (x, y, z)
        :param value: value with which 3D-array is to be filled
        :return: 3D-array
        """
    
        return [[[value for _ in xrange(dim[2])] for _ in xrange(dim[1])] for _ in xrange(dim[0])]
    
    if __name__ == "__main__":
        array = three_d_array(False, *(2, 3, 1))
        x = len(array)
        y = len(array[0])
        z = len(array[0][0])
        print x, y, z
    
        array[0][0][0] = True
        array[1][1][0] = True
    
        print array
    

    Prefer to use numpy.ndarray for multi-dimensional arrays.

提交回复
热议问题