发生异常的原因是and隐式调用bool。首先在左侧操作数上(如果左侧操作数为True),然后在右侧操作数上。所以x and y等于bool(x) and bool(y)。
然而,bool在numpy.ndarray(如果它包含多个元素)将抛出你已经看到了异常:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
该bool()电话是隐含在and,而且在if,while,or,所以任何的下面的示例也将失败:
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Python中还有更多函数和语句可以隐藏bool调用,例如,2 < x < 10这只是另一种编写方式2 < x and x < 10。而and将调用bool:bool(2 < x) and bool(x < 10)。
在元素方面等价物and将是np.logical_and功能,同样可以使用np.logical_or等同的or。
对于布尔数组-和比较喜欢的<,<=,==,!=,>=和>对NumPy的数组返回布尔NumPy的阵列-你也可以使用逐元素按位功能(和运营商): np.bitwise_and(&运营商)
>>> np.logical_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> np.bitwise_and(arr > 1, arr < 3)
array([False, True, False], dtype=bool)
>>> (arr > 1) & (arr < 3)
array([False, True, False], dtype=bool)
和bitwise_or(|运算子):
>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False, True], dtype=bool)
>>> (arr <= 1) | (arr >= 3)
array([ True, False, True], dtype=bool)
逻辑和二进制函数的完整列表可以在NumPy文档中找到: