python - Python 的双面不等式是如何工作的?为什么它不适用于 numpy 数组?

标签 python numpy comparison operators boolean-expression

在 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 to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < 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/

相关文章:

python - 在python中读取时将文本的所有值转换为int

python - QTreeWidget 中的目录树

python - Pandas Dataframe 多色线图

python - 在 Python 中,有没有办法保存/转储/序列化 PDB 调试 session ?

python - 矢量化批量图像像素查找 numpy 数组

python - 使用由少数元素构成的向量来平滑曲线?

python - 从Python中的散点图中查找点的密度

vb.net - 搜索特殊字符(例如accute等)的变体时比较字符串

.net - SSCLI 2.0 (ROTOR) 和 .NET 有什么区别?

algorithm - 在大型文件中查找部分相似的文件