我真的很困惑为什么出现此错误。这是我的代码:
import numpy as np
x = np.array([0, 0])
y = np.array([10, 10])
a = np.array([1, 6])
b = np.array([3, 7])
points = [x, y, a, b]
max_pair = [x, y]
other_pairs = [p for p in points if p not in max_pair]
>>>ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()
(a not in max_paix)
>>>ValueError: The truth ...
令我感到困惑的是,以下各项工作正常:
points = [[1, 2], [3, 4], [5, 7]]
max_pair = [[1, 2], [5, 6]]
other_pairs = [p for p in points if p not in max_pair]
>>>[[3, 4], [5, 7]]
([5, 6] not in max_pair)
>>>False
为什么在使用numpy数组时会发生这种情况?是not in/in暧昧所有脑干?
使用的正确语法是什么any()\all()?
numpy数组定义了一个自定义的相等运算符,即它们是实现__eq__magic函数的对象。因此,==运算符和依赖于这种相等性的所有其他功能/运算符称为此自定义相等性函数。
Numpy的相等性基于数组的元素明智比较。因此,作为回报,您将获得另一个具有布尔值的numpy数组。例如:
x = np.array([1,2,3])
y = np.array([1,4,5])
x == y
退货
array([ True, False, False], dtype=bool)
但是,in与列表结合使用的运算符要求仅返回单个布尔值的相等比较。这就是错误要求all或的原因any。例如:
any(x==y)
返回,True因为结果数组的至少一个值是True。相反
all(x==y) 
返回False因为不所有所得阵列的值True。
因此,在您的情况下,解决该问题的方法如下:
other_pairs = [p for p in points if all(any(p!=q) for q in max_pair)]
并print other_pairs打印预期结果
[array([1, 6]), array([3, 7])]
为什么这样?好,我们来看一个项目p从点,其中任何的条目是不相等的条目所有项目q从max_pair。
| 归档时间: | 
 | 
| 查看次数: | 11333 次 | 
| 最近记录: |