Multidimensional array in Python

前端 未结 12 1495
独厮守ぢ
独厮守ぢ 2021-02-04 15:49

I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:

double dArray[][][] = new double[x.l         


        
相关标签:
12条回答
  • 2021-02-04 16:21

    If you restrict yourself to the Python standard library, then a list of lists is the closest construct:

    arr = [[1,2],[3,4]]
    

    gives a 2d-like array. The rows can be accessed as arr[i] for i in {0,..,len(arr}, but column access is difficult.

    If you are willing to add a library dependency, the NumPy package is what you really want. You can create a fixed-length array from a list of lists using:

    import numpy
    arr = numpy.array([[1,2],[3,4]])
    

    Column access is the same as for the list-of-lists, but column access is easy: arr[:,i] for i in {0,..,arr.shape[1]} (the number of columns).

    In fact NumPy arrays can be n-dimensional.

    Empty arrays can be created with

    numpy.empty(shape)
    

    where shape is a tuple of size in each dimension; shape=(1,3,2) gives a 3-d array with size 1 in the first dimension, size 3 in the second dimension and 2 in the 3rd dimension.

    If you want to store objects in a NumPy array, you can do that as well:

     arr = numpy.empty((1,), dtype=numpy.object)
     arr[0] = 'abc'
    

    For more info on the NumPy project, check out the NumPy homepage.

    0 讨论(0)
  • 2021-02-04 16:25

    Another option is to use a dictionary:

    >>> from collections import defaultdict
    >>> array = defaultdict(int) # replace int with the default-factory you want
    >>> array[(0,0)]
    0
    >>> array[(99,99)]
    0
    

    You'll need to keep track of the upper & lower bounds as well.

    0 讨论(0)
  • 2021-02-04 16:27

    Take a look at numpy

    here's a code snippet for you

    import numpy as npy
    
    d = npy.zeros((len(x)+1, len(y)+1, len(x)+len(y)+3))
    d[0][0][0] = 0 # although this is unnecessary since zeros initialises to zero
    d[i][j][k] = npy.inf
    

    I don't think you need to be implementing a scientific application to justify the use of numpy. It is faster and more flexible and you can store pretty much anything. Given that I think it is probably better to try and justify not using it. There are legitimate reasons, but it adds a great deal and costs very little so it deserves consideration.

    P.S. Are your array lengths right? It looks like a pretty peculiar shaped matrix...

    0 讨论(0)
  • 2021-02-04 16:29

    I've just stepped into a similar need and coded this:

    def nDimensionsMatrix(dims, elem_count, ptr=[]):
        if (dims > 1):
            for i in range(elem_count[dims-1]):
                empty = []
                ptr.append(empty)
                nDimensionsMatrix(dims-1, elem_count, empty)
            return ptr
        elif dims == 1:
            ptr.extend([0 for i in range(elem_count[dims])])
            return ptr
    
    matrix = nDimensionsMatrix(3, (2,2,2))
    

    I'm not looking at speed, only funcionality ;)

    I want to create a matrix with N dimensions and initialize with 0 (a elem_count number of elements in each dimension).

    Hope its helps someone

    0 讨论(0)
  • 2021-02-04 16:32

    Probably not relevant for you but if you are doing serious matrix work see numpy

    0 讨论(0)
  • 2021-02-04 16:32

    For numeric data, Numpy Arrays:

    >>> matrix1 = array(([0,1],[1,3]))
    >>> print matrix1
    [[0 1]
    [1 3]]
    

    For general data (e.g. strings), you can use a list of lists, list of tuples, ...

    matrix2 = [['a','b'], ['x','y']]
    
    0 讨论(0)
提交回复
热议问题