Skip to main content
 首页 » 编程设计

python之Numpy 数组 __contains__ 检查

2024年11月01日10小虾米

我得到了一个数组:

temp = np.empty(5, dtype=np.ndarray)  
temp[0] = np.array([0,1]) 

我想检查 np.array([0,1]) in temp,在上面的示例中显然是,但代码返回 false。我也试过 temp.__contains__(np.array([0,1])) 但也返回 false。为什么是这样?它不应该返回 true 吗?

编辑:

所以 __contain__ 不会工作。有没有其他的检查方式?

请您参考如下方法:

一般来说,在 python 中,您需要了解的一件事是,从语义上讲,__contains__ 是基于 __eq__ 的,即它寻找满足 == 谓词。 (当然,可以覆盖 __contains__ 运算符来做其他事情,但那是另一回事)。

现在,对于 numpy 数组,__eq__ 根本不返回 bool。每个使用 numpy 的人都在某个时候遇到过这个错误:

if temp == temp2: 
   print 'ok' 
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

这意味着,考虑到 __contains__ 和 ndarray.__eq__ 的语义冲突,此操作不会执行您想要的操作也就不足为奇了。

对于您发布的代码,将 temp 设置为 np.array 而不是 list 并没有明显的优势。在任何一种情况下,您都可以“模拟” __contains__ 的行为,例如:

temp2 = np.array([0,1]) 
any( (a == temp2).all() for a in temp if a is not None ) 

如果您首先解释为什么选择使用异构 np.array,我可能会提出更详细的解决方案。

当然,如果没有@user2357112 到this question 的链接,这个答案就不会完整。 .