检查变量是否为None或numpy.array时发生ValueError [英] ValueError when checking if variable is None or numpy.array
问题描述
我想检查变量是否为None或numpy.array.我已经实现了check_a
函数来做到这一点.
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)
但是,此代码引发ValueError.什么是直截了当的方式?
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()
推荐答案
使用not a
测试a
是否为None
假定a
的其他可能值的真实值为True
.但是,大多数NumPy数组根本没有真值,因此not
不能应用于它们.
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.
如果要测试对象是否为None
,最通用,最可靠的方法是直接对None
使用is
检查:
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:
...
这不依赖于具有真值的对象,因此它适用于NumPy数组.
This doesn't depend on objects having a truth value, so it works with NumPy arrays.
请注意,测试必须是is
,而不是==
. is
是对象身份测试. ==
就是参数说的是什么,NumPy数组说这是广播的元素等式比较,产生一个布尔数组:
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()
另一方面,如果要测试对象是否为NumPy数组,则可以测试其类型:
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:
...
您还可以使用isinstance
,对于该类型的子类(如果需要的话),它还将返回True
.考虑到np.matrix
的可怕和不兼容,您可能实际上不希望这样做:
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:
...
这篇关于检查变量是否为None或numpy.array时发生ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!