Python: check if a list is multi-dimensional or one-dimensional

I am currently programming in python, and I have created a method that enters a list from the user, not knowing whether it is multidimensional or one-dimensional. how can i check Sample:


def __init__(self,target):    
    for i in range(len(target[0])):
        w[i]=np.random.rand(len(example[0])+1)

target is a list. the problem is that the target [0] may be int.

+5
source share
3 answers

I think you just want isinstance ?

Usage example:

>>> a = [1, 2, 3, 4]
>>> isinstance(a, list)
True
>>> isinstance(a[0], list)
False
>>> isinstance(a[0], int)
True
>>> b = [[1,2,3], [4, 5, 6], [7, 8, 9]]
>>> isinstance(b[0], list)
True
+9
source

According to the comments, you still convert your input to a numpy array. Since it is np.arrayalready processing the determination of the depth of input lists, it is easier to find out the number of dimensions from this array than from nested lists.

, shape, , len(myarray.shape) . ,

>>> import numpy as np
>>> a = np.array([[1,2,3],[1,2,3]])
>>> len(a.shape)
2
+7

If you like to know how many dimensions are in the list, you can use this piece of code:

def test_dim(testlist, dim=0):
   """tests if testlist is a list and how many dimensions it has
   returns -1 if it is no list at all, 0 if list is empty 
   and otherwise the dimensions of it"""
   if isinstance(testlist, list):
      if testlist == []:
          return dim
      dim = dim + 1
      dim = test_dim(testlist[0], dim)
      return dim
   else:
      if dim == 0:
          return -1
      else:
          return dim
a=[]
print test_dim(a)
a=""
test_dim(a)
print test_dim(a)
a=["A"]
print test_dim(a)
a=["A", "B", "C"]
print test_dim(a)
a=[[1,2,3],[1,2,3]]
print test_dim(a)
a=[[[1,2,3],[4,5,6]], [[1,2,3],[4,5,6]], [[1,2,3],[4,5,6]]]
print test_dim(a)
+5
source

All Articles