[英]Python check if list in list of lists with numpy arrays
I want to check if my query
which is of type list
is in the database
(a list
of lists
). 我想检查我
query
这类型的list
是在database
(一个list
的lists
)。 In the example below it is. 在下面的示例中。
query = [np.array([[4,3],[6,4]]),5,2,1,5]
database = [ [np.array([[8,5],[2,1]]),5,3,1,9],
[np.array([[4,3],[6,4]]),5,2,1,5],
[np.array([[7,2],[6,4]]),0,0,8,5]]
I have tried this: 我已经试过了:
np.any([(query==data) for data in database])
However, I get the following error: 但是,出现以下错误:
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
Try this: 尝试这个:
query = [i.tolist() if isinstance(i, np.ndarray) else i for i in query]
print(np.any([[i.tolist() if isinstance(i, np.ndarray) else i for i in data] == query for data in database]))
Output: 输出:
True
Since np.array_equal
can accept arrays or scalars, you could use it this way: 由于
np.array_equal
可以接受数组或标量,因此可以通过以下方式使用它:
In [107]: any(all(np.array_equal(datum, q) for datum, q in zip(data, query)) for data in database)
Out[107]: True
If your scalars are floats, you may wish to use np.allclose
instead of np.array_equal
since testing for exact float equality is often not desireable: 如果标量是浮点数,则可能不希望使用
np.allclose
而不是np.array_equal
因为通常不需要测试精确的浮点相等性:
In [108]: np.array_equal(0.1+0.2, 0.3)
Out[108]: False
In [109]: np.allclose(0.1+0.2, 0.3)
Out[109]: True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.