13

I am currently programing in python and I created a method that inputs list from the user, without knowing whether he is multidimensional or one dimensional. how do 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 the list. the problem is that target[0] might be int.

jamylak
  • 128,818
  • 30
  • 231
  • 230
user2129468
  • 681
  • 3
  • 8
  • 12

5 Answers5

21

I think you just want isinstance ?

Example usage:

>>> 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
Jack
  • 20,735
  • 11
  • 48
  • 48
12

According to the comments, you are converting your input to a numpy array anyway. Since np.array already handles figuring out how deeply the input lists are nested, it is easier to find out the number of dimensions from that array than from the nested lists.

In particular, arrays have a shape attribute which is a tuple of the lengths of the array along each dimension, so len(myarray.shape) will tell you the number of dimensions. eg,

>>> import numpy as np
>>> a = np.array([[1,2,3],[1,2,3]])
>>> len(a.shape)
2
lvc
  • 34,233
  • 10
  • 73
  • 98
8

If you like to find out how many dimensions a list has you can use this snippet 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)
bunkus
  • 975
  • 11
  • 19
1

This is very simplified solution. In most cases a multi-dimensional list/array/matrix would contain a list object in the first index. That being said, in python since you don't need to define the data type, this could return incorrect if your list looks something link: [1, [2,3], 4]. -- Otherwise it should work for all normal multi-dimensional lists.

def is2DList(matrix_list):
  if isinstance(matrix_list[0], list):
    return True
  else:
    return False
# list
list_1 = [1,2,3,4] # 1 x 4
list_2 = [ [1,2,3],[3,4,5] ] # 2 x 2
list_3 = [1, [2,3], 4]

print(is2DList(list_1)) # False
print(is2DList(list_2)) # True
print(is2DList(list_3)) # False - incorrect result

See it in action: https://trinket.io/python/a937fe2f00

Ryan Jones
  • 11
  • 2
0

I think this is the more thorough version of what Ryan Jones proposed. This version checks every list in mylist:

def is2dlist(mylist):
    for item in mylist:
        if isinstance(item, list):
            continue
        else:
            return False
    return True
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • Note if you want to include strings and a list as opposed to just a list use: isinstance(item, (list, str) – TheTridentGuy supports Ukraine Apr 22 '22 at 14:38
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – user11717481 Apr 22 '22 at 15:36