Find the dimensions of a multidimensional Python array

前端 未结 4 1382
小鲜肉
小鲜肉 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

    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.

提交回复
热议问题