Python 检查变量是否为 None 或 numpy.array 时出现 ValueError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36783921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:20:34  来源:igfitidea点击:

ValueError when checking if variable is None or numpy.array

pythonnumpyis-empty

提问by rkjt50r983

I'd like to check if variable is None or numpy.array. I've implemented check_afunction 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()

回答by Jerfov2

Using not ato test whether ais Noneassumes that the other possible values of ahave a truth value of True. However, most NumPy arrays don't have a truth value at all, and notcannot be applied to them.

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

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

如果要测试对象是否为None,最通用、最可靠的方法是逐字使用is检查None

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

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

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

Note that the test has to be is, not ==. isis 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:

请注意,测试必须是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()


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

另一方面,如果你想测试一个对象是否是一个 NumPy 数组,你可以测试它的类型:

# 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 Truefor subclasses of that type (if that is what you want). Considering how terrible and incompatible np.matrixis, you may not actually want this:

您也可以使用isinstance,它也将返回True该类型的子类(如果这是您想要的)。考虑到多么可怕和不相容np.matrix,你可能并不真正想要这个:

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

回答by mimoralea

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.anyor a.all.

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

A workaround is to do:

一种解决方法是:

if not (a is None):
    pass

Not too pretty, but it does the job.

不太漂亮,但它可以完成工作。

回答by Itachi

You can see if object has shape or not

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

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