Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: check if list is multidimensional or one dimensional

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.

like image 314
user2129468 Avatar asked Apr 13 '13 07:04

user2129468


People also ask

How do I check if an array is 1D or 2D in Python?

Look for array. shape: if it comes like (2,) means digit at first place but nothing after after comma,its 1D. Else if it comes like (2,10) means two digits with comma,its 2D.

Is list multidimensional in Python?

Lists are a very widely use data structure in python. They contain a list of elements separated by comma. But sometimes lists can also contain lists within them. These are called nested lists or multidimensional lists.

Are Python lists one dimensional?

Python lists are one dimensional only.

How do you find the dimension of a list?

A list is identifiable by the square brackets that surround it, and individual values are separated by a comma. To get the length of a list in Python, you can use the built-in len() function. Apart from the len() function, you can also use a for loop and the length_hint() function to get the length of a list.


1 Answers

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
like image 186
Jack Avatar answered Oct 13 '22 20:10

Jack