正如您在侧边栏中看到的那样,ValueError 之前出现过很多次。
问题的核心在于 numpy 数组可以返回多个真值,而许多 Python 操作只期望一个。
我会举例说明:
In [140]: this=None
In [141]: if this:print 'yes'
In [142]: if this is None: print 'yes'
yes
In [143]: this=np.array([1,2,3])
In [144]: if this: print 'yes'
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [145]: if this is None: print 'yes'
In [146]: this and this
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [147]: [1,2,3] is None
Out[147]: False
In [148]: this is None
Out[148]: False
In [149]: [1,2,3]==3 # one value
Out[149]: False
In [150]: this == 3 # multiple values
Out[150]: array([False, False, True], dtype=bool)
像not 这样的逻辑运算通常返回一个简单的真/假,但对于数组,它们为数组的每个元素返回一个值。
In [151]: not [1,2,3]
Out[151]: False
In [152]: not None
Out[152]: True
In [153]: not this
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
在您的函数中,如果您不提供 f 2 个或更多参数,this 和 that 将具有值 None。安全的测试方法是使用is None 或is not None:
def f(some_stuff, this=None, that=None):
...do something...
if this is not None and that is not None:
perform_the_task()