DIEA
例外的原因是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 arrValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()>>> if arr: passValueError:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()>>> while arr: passValueError: The truth value of
an array with more than one element is ambiguous. Use a.any() or a.all()>>> arr or arrValueError: 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文档中可以找到逻辑和二进制函数的完整列表:“逻辑功能”“二进制操作”