脾气暴躁:需要帮助理解“ in”运算符会发生什么


问题内容

如果有人可以帮助我(并解释发生的事情),我将不胜感激。

这有效:

>>> from numpy import array
>>> a = array((2, 1))
>>> b = array((3, 3))
>>> l = [a, b]
>>> a in l
True

但这不是:

>>> c = array((2, 1))
>>> c in l
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我想复制的行为是:

>>> x = (2, 1)
>>> y = (3, 3)
>>> l2 = [x, y]
>>> z = (2, 1)
>>> z in l2
True

请注意,以上内容也适用于可变对象:

>>> x = [2, 1]
>>> y = [3, 3]
>>> l2 = [x, y]
>>> z = [2, 1]
>>> z in l2
True

当然知道:

>>> (a < b).all()
True

我尝试了(但失败了):

>>> (c in l).all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

问题答案:

Python之所以做出选择bool([False,True])True因为(说)任何非清空列表都具有布尔值True。

Numpy做出bool(np.array([False, True]))应该引发ValueError的选择。Numpy是从一些用户的角度设计的,一些用户可能想知道数组中的 任何
元素是否为True,而其他用户可能想知道数组中的 所有
元素是否为True。由于用户的愿望可能有冲突,因此NumPy拒绝猜测。它会引发ValueError并建议使用np.anynp.all(尽管如果您希望复制类似Python的行为,则可以使用len)。

在评估时c in l,Python会cl开头的每个元素进行比较a。它评估bool(c==a)。我们得到bool(np.array([True True])),它引发ValueError(由于上述原因)。

由于numpy拒绝猜测,因此您必须具体。我建议:

import numpy as np
a=np.array((2,1))
b=np.array((3,3))
c=np.array((2,1))
l=[a,b]
print(any(np.all(c==elt) for elt in l))
# True