Sunday 14 January 2018

python: how to identify if a variable is an array or a scalar

itemprop="text">

I have a function that takes the
argument NBins. I want to make a call to this function with a
scalar 50 or an array [0, 10, 20, 30].
How can I identify within the function, what the length of
NBins is? or said differently, if it is a scalar or a vector?




I tried
this:



>>>
N=[2,3,5]
>>> P = 5
>>>
len(N)
3
>>> len(P)
Traceback (most recent call
last):
File "", line 1, in
TypeError:
object of type 'int' has no len()

>>>



As you see, I can't
apply len to P, since it's not an
array.... Is there something like isarray or
isscalar in
python?



thanks



Answer




>>> isinstance([0, 10,
20, 30], list)
True
>>> isinstance(50,
list)

False


To
support any type of sequence, check collections.Sequence
instead of
list.



note:
isinstance also supports a tuple of classes, check
type(x) in (..., ...) should be avoided and is
unnecessary.



You may also wanna check
not isinstance(x, (str, unicode))



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...