有代码:
import numpy as np
def check(x):
if x == None:
print('x is None')
check(np.array([1,2]))
x
可以是None或np.ndarray,所以我想检查x
是否为无或np.ndarray,但如果我将np.ndarray传递给check
,它将会提出错误,
因为np.ndarray ==无应使用np.any()
或np.all()
。那我该怎么办?
答案 0 :(得分:1)
试试这个:
import numpy as np
def check(x):
if type(x) is np.ndarray:
print('x is numpy.ndarray')
else:
raise ValueError("x is None")
check(np.array([1, 2]))
答案 1 :(得分:1)
首选type(x)
:使用isinstance
。
来自PEP 8:
对象类型比较应始终使用
isinstance()
而不是。{ 直接比较类型。
在您的示例中:使用if isinstance(x, np.ndarray):
x
是否为None
选项1:
使用elif x is None:
。这明确检查x
是否为无。
选项2:
使用elif not x:
。这利用了None
的“Falsiness”,但是如果x
是其他“Falsey”值,例如np.nan
,则它也会评估为True ,或空数据结构。
答案 2 :(得分:0)
它引发值错误的原因是,对于Numpy的最新版本,即使与None进行比较,__eq__
数组覆盖也会进行元素对象比较。
使用Numpy 1.12.1:
In [2]: if np.array([1,2,3]) == None:
...: print('Equals None')
...: else:
...: print('Does not equal None')
...:
/home/user/Work/SO/bin/ipython:1: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
#!/home/user/Work/SO/bin/python3
Does not equal None
和Numpy 1.13.1:
In [1]: if np.array([1,2,3]) == None:
...: print('Equals None')
...: else:
...: print('Does not equal None')
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-06133f6732e1> in <module>()
----> 1 if np.array([1,2,3]) == None:
2 print('Equals None')
3 else:
4 print('Does not equal None')
5
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
错误非常自我解释。与纯Python序列的行为相比,Numpy对数组的真实性有不同的看法。
为了检查某个对象是否为singleton value None,您应该使用identity comparison,并解释here:
def check(x):
if x is None:
print('x is None')
else:
print('x is not None')