简体   繁体   中英

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.

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? instead of changing every numpy array to list.

You cannot avoid one iteration through the lst to modify its elements (numpy arrays) somehow. 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])

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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