这个问题在这里已有答案:
__contains__如何为ndarrays工作? 2个答案我有一些代码,我希望它能做到这一点:
>> x=np.zeros((40,2)) >> x[31]=(12,15) >> y=x.copy() >> y[31]=(12,4) #the following behavior is correct, but the syntax is unwieldy with the #conversions to float and list, quite annoying >> e=[12.,15.] >> e in x.tolist() True >> e in y.tolist() False但是,在调试过程中我发现了以下奇怪的行为:
>> e in x True >> e in y True即使
>> f=(8,93) >> f in x False我的问题有两个:
a)numpy在这里做什么来产生这个结果?
b)除了使用tolist和float转换之外,还有其他方法可以完成此检查(不使用python级别for循环)吗? 这种设计不明显,不易维护。
This question already has an answer here:
How does __contains__ work for ndarrays? 2 answersI have some code, and what I would like it to do is this:
>> x=np.zeros((40,2)) >> x[31]=(12,15) >> y=x.copy() >> y[31]=(12,4) #the following behavior is correct, but the syntax is unwieldy with the #conversions to float and list, quite annoying >> e=[12.,15.] >> e in x.tolist() True >> e in y.tolist() FalseHowever, in the course of debugging I observed the following odd behavior:
>> e in x True >> e in y Trueeven though
>> f=(8,93) >> f in x FalseMy question is twofold:
a) What is numpy doing here to produce this result?
b) Is there some way to accomplish this check other than using tolist and float conversion as I have here (without using a python-level for loop)? This design is not obvious and not easily maintainable.
最满意答案
我认为 in会给你一个相当于np.any(y == e) ,其中维度是自动广播的。 如果你看y == e (粘贴在这个答案的底部)它有一个True元素。 比我更了解情况的人会知道究竟发生了什么。
可能有一种更简洁的方法,但我建议这样做而不是转换为列表:
>>> np.any(np.all(x == e, axis=-1)) True >>> np.any(np.all(y == e, axis=-1)) False输出y == e看起来像
>>> y == e array([[False, False], ... [False, False], [ True, False], [False, False], ... [False, False]], dtype=bool)I think that in will give you a result equivalent to np.any(y == e) where the dimensions are broadcasted automatically. If you look at y == e (pasted at the bottom of this answer) it has a single True element. Someone more knowledgeable than me will know what's really going on.
There is probably a cleaner way to do it but I would suggest this instead of converting to a list:
>>> np.any(np.all(x == e, axis=-1)) True >>> np.any(np.all(y == e, axis=-1)) FalseOutput of y == e looks like
>>> y == e array([[False, False], ... [False, False], [ True, False], [False, False], ... [False, False]], dtype=bool)更多推荐
发布评论