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?
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With