使用
nota测试是否
a是
None假设的其他可能值
a有真值
True。但是,大多数NumPy数组根本没有真值,
not因此无法应用于它们。
如果要测试对象是否为
None,最通用,最可靠的方法是直接使用以下
is检查
None:
if a is None: ...else: ...
这不依赖于具有真值的对象,因此它适用于NumPy数组。
注意测试必须是
is,不是
==。
is是对象身份测试。
==无论参数说什么,NumPy数组都说这是广播的元素等式比较,产生一个布尔数组:
>>> a = numpy.arange(5)>>> a == Nonearray([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: ...



