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

时间:2016-08-31 17:21:58

标签: python arrays python-2.7 list numpy

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.

3 个答案:

答案 0 :(得分:2)

def dimens(l):
    try:
        size = len(l)
    except TypeError: # not an iterable
        return 0
    else:
        if size: # non-empty iterable
            return 1 + max(map(dimens, l))
        else: # empty iterable
            return 1

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

Output

3
6

答案 1 :(得分:0)

Here's my function:

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

Testing:

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

Limitations:

  • Only goes up to three dimensions (this is enough for my application)
  • 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)

Can anyone do better?

答案 2 :(得分:0)

You can use isinstance method to distinguish between the two arrays

Lets consider the first list

a = [1,2,3]

Here the first element is an integer hence isinstance(a[0],int) will return true

For the second array b = [[1,2][3,4]] the first element is an array so isinstance(b[0],int) will return false. You can check the second list by using isinstance(b[0],list)

I am using list in place of array but it will work with arrays also