简体   繁体   English

检查 1D numpy 数组是否在 1D numpy arrays 和 None 的列表中

[英]Checking if 1D numpy array in a list of 1D numpy arrays and None

I want to check whether a 1D numpy array in the list of a 1D numpy arrays and None for an if condition.我想检查 1D numpy 数组是否在 1D numpy arrays 和 None 的列表中是否为 if 条件。

I did it like this:我是这样做的:

arr = np.array([1,2])
lst = [np.array([1,2]), np.array([3,4]), None, None]

if list(arr) in [list(i) for i in lst if i is not None]:
    print("Yes")

else:
    print("No")

but the size of the list and the numpy array can be much larger, so is there a more efficient way to do this?但是列表和 numpy 数组的大小可以大得多,那么有没有更有效的方法来做到这一点? instead of changing every numpy array to list.而不是将每个 numpy 数组更改为列表。

You cannot avoid one iteration through the lst to modify its elements (numpy arrays) somehow.您无法避免通过lst进行一次迭代以某种方式修改其元素(numpy 数组)。 But instead of creating a list of lists out of the numpy arrays, you can create a set of tuples instead and store it: set_of_arrays_as_tuples = set([tuple(array) for array in lst if array is not None])但不是从 numpy arrays 创建列表列表,而是创建一组元组并将其存储: set_of_arrays_as_tuples = set([tuple(array) for array in lst if array is not None])

Then, any subsequent query to check presence in the set can be done in constant time, instead of linear time:然后,任何后续查询以检查集合中的存在性都可以在常数时间内完成,而不是线性时间:

tuple(arr) in set_of_arrays_as_tuples

->True -> 真

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM