样例假设:设一变量v,v可以是numpy.ndarray,也可以是None,做v为numpy.ndarry与None值的判定
v 为 numpy.ndarray
In [1]: import numpy as np
In [2]: v = np.zeros((2,2))
In [3]: print(type(v))
<class 'numpy.ndarray'>
In [4]: print(v)
[[0. 0.]
[0. 0.]]
v 为 None
In [5]: v = None
In [6]: print(type(v))
<class 'NoneType'>
In [7]: print(v)
None
错误判定方法一:使用None == v进行判定
当v = None时通过
In [8]: v = None
In [9]: if None == v:
...: print("判定通过")
...: else:
...: print("判定通过")
判定通过
当v = np.zeros((2,2))报错
In [10]: v = np.zeros((2,2))
In [11]: if None == v:
...: print("判定通过")
...: else:
...: print("判定通过")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-10-cb564f23b615> in <module>
----> 1 if None == v:
2 print("判定通过")
3 else:
4 print("判定通过")
5
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
错误判定方法二:使用False == v.any()进行判定(来自错误判定方法一的提示)
当v = None时报错
In [12]: v = None
In [13]: if False == v.any():
...: print("判定通过")
...: else:
...: print("判定通过")
...:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-579411b4814e> in <module>
----> 1 if False == v.any():
2 print("判定通过")
3 else:
4 print("判定通过")
5
AttributeError: 'NoneType' object has no attribute 'any'
当v = np.zeros((2,2))通过
In [14]: v = np.zeros((2,2))
In [15]: if False == v.any():
...: print("判定通过")
...: else:
...: print("判定通过")
...:
判定通过
错误判定方法三:使用False == v.all()进行判定(来自错误判定方法一的提示)
当v = None时报错
In [16]: v = None
In [17]: if False == v.all():
...: print("判定通过")
...: else:
...: print("判定通过")
...:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-c879f04e8cf0> in <module>
----> 1 if False == v.all():
2 print("判定通过")
3 else:
4 print("判定通过")
5
AttributeError: 'NoneType' object has no attribute 'all'
当v = np.zeros((2,2))通过
In [18]: v = np.zeros((2,2))
In [19]: if False == v.all():
...: print("判定通过")
...: else:
...: print("判定通过")
...:
判定通过
错误判定方法四:使用v或not v进行判定(以not v为例,两者出错一致)
当v = None通过
In [20]: v = None
In [21]: if not v:
...: print("判定通过")
...: else:
...: print("判定通过")
...:
判定通过
当v = np.zeros((2,2))报错
In [22]: v = np.zeros((2,2))
In [23]: if not v:
...: print("判定通过")
...: else:
...: print("判定通过")
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-23-0396573717f2> in <module>
----> 1 if not v:
2 print("判定通过")
3 else:
4 print("判定通过")
5
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
正确判定方法:使用v is None判定
当v = None通过
In [24]: v = None
In [25]: if v is None:
...: print("判定通过")
...: else:
...: print("判定通过")
...:
判定通过
当v = np.zeros((2,2))通过
In [26]: v = np.zeros((2,2))
In [27]: if v is None:
...: print("判定通过")
...: else:
...: print("判定通过")
...:
判定通过