Find the dimensions of a multidimensional Python array

前端 未结 4 1379
小鲜肉
小鲜肉 2021-02-07 05:59

In Python, is it possible to write a function that returns the dimensions of a multidimensional array (given the assumption that the array\'s dimensions are not jagged)?

相关标签:
4条回答
  • 2021-02-07 06:20

    No, there's nothing built-in because with such "arrays"1 it can be jagged and the concept of "dimensions" or "shape" doesn't make any sense at all. So, you'll have to write your own. If you can make an assumption of uniformity along all dimensions, you can proceed as follows:

    dim1 = len(a)
    dim2 = len(a[0])
    dim3 = len(a[0][0])
    .
    .
    .
    

    It'd be pretty easy to make this recursive to handle all dimensions. This should do it:

    def dim(a):
        if not type(a) == list:
            return []
        return [len(a)] + dim(a[0])
    

    But if you need something like this, you might want to consider looking at NumPy arrays which have numpy.ndarray.shape which would give you what you're looking for.

    from numpy import array
    l = [[2, 3], [4, 2], [3, 2]]
    a = array(l)
    print a.shape
    

    Output

    (3, 2)
    

    1 In scare quotes because you're not really looking at array, you're looking at a list, or a list of lists, or a list of list of lists....

    0 讨论(0)
  • 2021-02-07 06:20

    That is not a multi-dimensional array. It is a list. It happens to contain other lists. There's nothing to say that your list could not be:

    [[2,3], [4,2], [3,2,4,5,6]]
    

    In which case, what value would you expect such a function to return?

    There is no general function that does what you ask, not least because Python itself does not define a matrix/array class. You certainly can write your own function which operates on iterable objects like lists and tuples if you are prepared to make assumptions, or write assertions, as to the uniformity of the list. Use len(a) for the first dimension, len(a[0]) for the second, and so on. Recursion will be your friend here.

    If you used a numpy array for your matrix, which to be honest would make a lot of sense, then your function would exist (it is the shape property of the ndarray class) and be meaningful.

    0 讨论(0)
  • 2021-02-07 06:30

    You can do it with numpy:

    import numpy
    l = [[2,3], [4,2], [3,2]]
    m = numpy.array(l)
    print m.shape
    

    But the shape of your second example is [2,2,2], not [1,4,5], unless I've misunderstood your question...

    0 讨论(0)
  • 2021-02-07 06:39

    Assuming the input array is not jagged :

    def arr_dimen(a):
      return [len(a)]+arr_dimen(a[0]) if(type(a) == list) else []
    
    0 讨论(0)
提交回复
热议问题