在 Python 中,您可以执行以下操作;
>>> 3 < 4 < 5
True
>>> 3 < 4 < 4
False
这是如何运作的?我本以为4 < 5
会返回一个 bool 值,所以 3 < True
应该返回 False
, 或 3 < 4
应该返回一个 bool 值,所以 True < 4
也许应该返回 True
如果True
可以转换为整数 1 吗?
为什么它不适用于 numpy 数组?
>>> 1 < np.array([1, 2, 3]) < 3
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
它可以用于 numpy 数组吗?
最佳答案
根据 the Python docs :
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
所以你的例子相当于:
1 < np.array([1, 2, 3]) and np.array([1, 2, 3]) < 3
所以每个子项都应该产生一个 bool 值。但是子项:
1 < np.array([1, 2, 3])
产生一个新的 numpy 数组,其中包含:
[False, True, True]
Python 试图将此值解释为 bool 值。它无法做到这一点,并产生错误消息:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我希望这里所需的表达式是:
(1 < np.array([1, 2, 3])).all() and (np.array([1, 2, 3]) < 3).all()
不能简化为使用比较链。
关于python - Python 的双面不等式是如何工作的?为什么它不适用于 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65849231/