检查变量是否为None或numpy.array时的ValueError

时间:2022-12-29 19:47:56

I'd like to check if variable is None or numpy.array. I've implemented check_a function to do this.

我想检查变量是否为None或numpy.array。我已经实现了check_a函数来执行此操作。

def check_a(a):
    if not a:
        print "please initialize a"

a = None
check_a(a)
a = np.array([1,2])
check_a(a)

But, this code raises ValueError. What is the straight forward way?

但是,这段代码引发了ValueError。什么是直接的方式?

ValueError                                Traceback (most recent call last)
<ipython-input-41-0201c81c185e> in <module>()
      6 check_a(a)
      7 a = np.array([1,2])
----> 8 check_a(a)

<ipython-input-41-0201c81c185e> in check_a(a)
      1 def check_a(a):
----> 2     if not a:
      3         print "please initialize a"
      4 
      5 a = None

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

1 个解决方案

#1


69  

Just do it!:

去做就对了!:

if a is None:
    ...
else:
    ...

Or if you want to be more explicit:

或者如果你想更明确:

# be careful not to check for np.array but for np.ndarray!
if type(a) is np.ndarray:
    ...
else:
    ...

Also if you use isinstance, it will also return True for subclasses of that type (if that is what you want):

此外,如果您使用isinstance,它也将为该类型的子类返回True(如果这是您想要的):

# be careful not to check for np.array but for np.ndarray!
if isinstance(a, np.ndarray):
    ...
else:
    ...    

#1


69  

Just do it!:

去做就对了!:

if a is None:
    ...
else:
    ...

Or if you want to be more explicit:

或者如果你想更明确:

# be careful not to check for np.array but for np.ndarray!
if type(a) is np.ndarray:
    ...
else:
    ...

Also if you use isinstance, it will also return True for subclasses of that type (if that is what you want):

此外,如果您使用isinstance,它也将为该类型的子类返回True(如果这是您想要的):

# be careful not to check for np.array but for np.ndarray!
if isinstance(a, np.ndarray):
    ...
else:
    ...