How to determine the dimensions of a mix of lists and arrays?
<p>Consider an object that is a list of arrays: </p>

<p><code>a=[array([1,2,3]),array(2,5,10,20)]</code></p>

<p>In its own funny way, this thing has two dimensions. The list itself is one dimension, and it contains objects which are 1D. Is there an easy way to distinguish between <code>a</code> above and a list like <code>b=[1,3,6,9,11]</code> which is simply 1D, and <code>c=1</code>, which is a 0D scalar? I want a function <code>dimens()</code> such that <code>dimens(a)</code> returns <code>2</code>, <code>dimens(b)</code> returns <code>1</code>, and <code>dimens(c)</code> returns <code>0</code>.</p>

<p>I am doing it by testing the shape of the first element in the list, but I feel like there may be a cleaner approach.</p>

<p>Here's my function:</p>

<pre><code>def dimens(x):
    s=shape(x)
    if len(s)==0:
        return 0 #the input was a scalar
    s2=shape(x[0])
    if len(s2)==0:
        return 1 #each element of the list was a scalar
    else:
        #each element of the list was a vector or array
        if len(s2)==1:
            if len(shape(s2[0]))==0:
                return 2 #the first element of the top list was a 1D vector and the first element of that vector was a scalar
        return 3 #there were more than 2 dimensions involved
</code></pre>

<p>Testing:</p>

<pre><code>a=[array([1,2,3]),array([2,5,10,20])]
b=[1,3,6,9,11]
c=1
d=[[a]]+[[a]]

print dimens(a)
2
print dimens(b)
1
print dimens(c)
0
print dimens(d)
3
</code></pre>

<p>Limitations:</p>

<ul>
<li>Only goes up to three dimensions (this is enough for my application)</li>
<li>Only tests the first element, so it assumes that each element has the same dimensionality (which is fine for my application since my 2D case will be a list of all arrays, not a list that has a mix of arrays and scalars)</li>
</ul>

<p>Can anyone do better?</p>

python arrays list numpy