python - 数组列表的成员资格 : ValueError: The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all() 错误问题

标签 python valueerror

Q = [np.array([0, 1]), np.array([1, 2]), np.array([2, 3]), np.array([3, 4])]
for q in Q:
    print(q in Q)

运行上面的代码,它在第一次迭代时给了我结果 'True',而之后 ValueError 出来了。

True

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我不知道为什么它在第二次迭代时开始出错。任何人都可以帮助我PLZ..

最佳答案

本质上,您不能使用 in 来测试 Python 列表中的 numpy 数组。它只会对第一个元素起作用,因为 Python 测试相等性的方式进行了优化。

发生的事情是 list.__contains__ 的实现(in 遵循),首先使用快捷方式更快地找到匹配项 检查身份。大多数使用 Python 的人都知道这是 is operator .这比 == 相等性检查要快,因为所有 is 要做的就是查看两个对象的指针是否相同,值得先检查 。任何 Python 对象(包括 numpy 数组)的身份测试都是一样的。

如果是用 Python 编写的,实现基本上是这样的:

def __contains__(self, needle):
    for elem in self:
        if needle is elem or needle == elem:
            return True
    return False

那么你的 numpy 数组列表会发生什么:

  • for q in Q,第 1 步:q = Q[0]

    • q in QQ.__contains__(Q[0]) 相同
      • Q[0] is self[0] => True!
  • for q in Q,第 2 步:q = Q[1]

array([False, False]) 结果是不是 bool 值,但是if想要一个 bool 结果,所以通过到(C 等价于)bool() function . bool(array([False, False])) 产生你看到的错误。

或者,手动完成:

>>> import numpy as np
>>> Q = [np.array([0, 1]), np.array([1, 2]), np.array([2, 3]), np.array([3, 4])]
>>> Q[0] is Q[0]
True
>>> Q[1] is Q[0]
False
>>> Q[1] == Q[0]
array([False, False])
>>> bool(Q[1] == Q[0])
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()

您必须使用 any()numpy.array_equal()创建不使用(正常)== 相等检查的 list.__contains__ 版本:

def list_contains_array(lst, arr):
    return any(np.array_equal(arr, elem) for elem in lst)

然后您可以使用它为您的循环获取 True:

>>> for q in Q:
...     print(list_contains_array(Q, q))
...
True
True
True
True

关于python - 数组列表的成员资格 : ValueError: The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all() 错误问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72076793/

相关文章:

python - PIL 值错误 : Images do not match

python - HyperlinkedIdentityField + @detail_route

python - read_csv 获取发生异常的行

python - Pip 安装返回 ValueError

python - 如何使用 numpy.all() 或 numpy.any()?

python-2.7 - 如何在 Pandas 中使用 base 10 错误修复 int() 的无效文字

python - Django 属性错误 : 'Alias' object has no attribute 'urls'

python - 如何使用 re 替换和移动 python 中的字符串模式?

python - ReadDirectoryChangesW无法检测和处理监视目录的删除

python - 创建 Shapely 多边形的数据框给出 "ValueError: A LinearRing must have at least 3 coordinate tuples"