且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

numpy:具有多个元素的数组的真值不明确

更新时间:2022-05-18 03:20:39

Numpy数组定义了一个自定义的相等运算符,即它们是实现__eq__魔术函数的对象.因此,==运算符和所有依赖于这种相等性的其他函数/运算符都称为此自定义相等性函数.

Numpy arrays define a custom equality operator, i.e. they are objects that implement the __eq__ magic function. Accordingly, the == operator and all other functions/operators that rely on such an equality call this custom equality function.

Numpy的相等性基于数组的逐元素比较.因此,作为回报,您将获得另一个具有布尔值的numpy数组.例如:

Numpy's equality is based on element-wise comparison of arrays. Thus, in return you get another numpy array with boolean values. For instance:

x = np.array([1,2,3])
y = np.array([1,4,5])
x == y

返回

array([ True, False, False], dtype=bool)

但是,将in运算符与 lists 结合使用时,要求相等比较仅返回单个布尔值.这就是错误要求allany的原因.例如:

However, the in operator in combination with lists requires equality comparisons that only return a single boolean value. This is the reason why the error asks for all or any. For instance:

any(x==y)

返回True,因为结果数组的至少一个值为True. 相反

returns True because at least one value of the resulting array is True. In contrast

all(x==y) 

返回False,因为不是结果数组的所有值都是True.

returns False because not all values of the resulting array are True.

因此,在您的情况下,解决该问题的方法如下:

So in your case, a way around the problem would be the following:

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])]

为什么呢?好吧,我们从 points 中寻找一个 p 项,其中任何项与 all 项不相等 max_pair 中的项目 q .

Why so? Well, we look for an item p from points where any of its entries are unequal to the entries of all items q from max_pair.