问题:检查变量是否为None或numpy.array时发生ValueError

我想检查变量是否为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)

但是,此代码引发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()

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

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                                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()

回答 0

使用not a测试是否aNone假设的其他可能值a有真值True。但是,大多数NumPy数组根本没有真值,not因此无法应用于它们。

如果要测试某个对象是否为None,最通用,最可靠的方法就是直接使用以下is检查None

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

这不依赖于具有真值的对象,因此它适用于NumPy数组。

注意测试必须是is,不是==is是对象身份测试。==无论参数说什么,NumPy数组都说这是广播的元素等式比较,产生一个布尔数组:

>>> a = numpy.arange(5)
>>> a == None
array([False, False, False, False, False])
>>> if a == None:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
 Use a.any() or a.all()

另一方面,如果要测试对象是否为NumPy数组,则可以测试其类型:

# Careful - the type is np.ndarray, not np.array. np.array is a factory function.
if type(a) is np.ndarray:
    ...
else:
    ...

您还可以使用isinstance,它还会返回True该类型的子类(如果您要的话)。考虑到可怕和不兼容np.matrix,您可能实际上不希望这样做:

# Again, ndarray, not array, because array is a factory function.
if isinstance(a, np.ndarray):
    ...
else:
    ...    

Using not a to test whether a is None assumes that the other possible values of a have a truth value of True. However, most NumPy arrays don’t have a truth value at all, and not cannot be applied to them.

If you want to test whether an object is None, the most general, reliable way is to literally use an is check against None:

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

This doesn’t depend on objects having a truth value, so it works with NumPy arrays.

Note that the test has to be is, not ==. is is an object identity test. == is whatever the arguments say it is, and NumPy arrays say it’s a broadcasted elementwise equality comparison, producing a boolean array:

>>> a = numpy.arange(5)
>>> a == None
array([False, False, False, False, False])
>>> if a == None:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
 Use a.any() or a.all()

On the other side of things, if you want to test whether an object is a NumPy array, you can test its type:

# Careful - the type is np.ndarray, not np.array. np.array is a factory function.
if type(a) is np.ndarray:
    ...
else:
    ...

You can also use isinstance, which will also return True for subclasses of that type (if that is what you want). Considering how terrible and incompatible np.matrix is, you may not actually want this:

# Again, ndarray, not array, because array is a factory function.
if isinstance(a, np.ndarray):
    ...
else:
    ...    

回答 1

如果您尝试执行非常相似的操作:a is not None,则会出现相同的问题。也就是说,Numpy抱怨必须使用a.anya.all

解决方法是:

if not (a is None):
    pass

不太漂亮,但是可以做到。

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):
    pass

Not too pretty, but it does the job.


回答 2

您可以查看对象是否具有形状

def check_array(x):
    try:
        x.shape
        return True
    except:
        return False

You can see if object has shape or not

def check_array(x):
    try:
        x.shape
        return True
    except:
        return False

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。