Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find dimension of a nested tuple?

I have a tuple that looks like this

  array=(1,2,3,4)
  lenM = numpy.shape(array)
  print lenM
  (4,)

  if not lenM[1]:
       "Code"

Now how do I automate the my code to find if the tuple is one dimensional or two dimensional?

like image 648
Spandyie Avatar asked Dec 06 '15 21:12

Spandyie


People also ask

How do I find the length of a nested tuple in Python?

The length is a measure of the number of items in the tuple, and is obtained using the method named len(). Listing 6 shows the output produced by the code in Listing 5, including the length of the new tuple containing the two nested tuples.

How do you find the tuple dimension in Python?

The shape of a simple Python tuple or list can be obtained with the built-in len() function. len() will return an integer that describes the number of objects in the tuple or list.

How do you measure the size of a tuple?

Finding the size or length of a tuple is a pretty straightforward process. The size of a tuple represents the number of objects present in the tuple. The syntax used for finding the size is len(). This method returns the number of elements/objects present in the tuple.

How many dimensions is a tuple?

The dimensions of the tuple are not known, but are either one, or two dimensions. Tuples can take the form: One dimensional, from 1 element to n, examples. Two dimensional examples.


2 Answers

You can use numpy.ndim for this:

In [4]: np.ndim((1,2,3,4))
Out[4]: 1
In [5]: np.ndim(((1,2),(3,4)))
Out[5]: 2
like image 152
xnx Avatar answered Oct 11 '22 03:10

xnx


array=(1,2,3,4)
lenM = numpy.shape(array)
print lenM
(4,)

if len(lenM) == 1:
    "1 dimensional code"
elif len(lenM) == 2:
    "2 dimensional code"

len(lenM) will tell you if there is more than one dimension in array. If len(lenM) is 1, there's only one dimension. if array has more than one dimension, lenM will have more than one element.

like image 44
Tom Barron Avatar answered Oct 11 '22 01:10

Tom Barron