EL_DON - 1 year ago 99
Python Question

# How to determine the dimensions of a mix of lists and arrays?

Consider an object that is a list of arrays:

`a=[array([1,2,3]),array(2,5,10,20)]`

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
`a`
above and a list like
`b=[1,3,6,9,11]`
which is simply 1D, and
`c=1`
, which is a 0D scalar? I want a function
`dimens()`
such that
`dimens(a)`
returns
`2`
,
`dimens(b)`
returns
`1`
, and
`dimens(c)`
returns
`0`
.

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.

for both numpy and pure python lists:

``````def dimens(l):
try:
size = len(l)
except TypeError:
return 0
else:
if size:
return 1 + max(map(dimens, l))
else:
return 1

print(dimens([[1,2,3],[2,5,10,[1,2]]]))
print(dimens(zeros([6,5,4,3,2,1])))
``````

Output

``````3
6
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download