Search code examples
pythonarrayslistnumpycontains

How to check if element in array contains any values from a list Python


I have a list of words:

list1 = ['foo', 'baz', 'bat']

And an array of strings:

list2 = ['foo word word word', 'word baz word word', 'word word word word', 'word word bat word']
string_arr = np.array(list2)

I want to enumerate through the array and return a boolean if the element in the array contains any of the values in the list. The output to be a list of booleans:

[True, True, False, True]

Right now all I have is this code which just gives me a list of indices, which I don't want:

idx_mask = [idx for idx, element in enumerate(string_arr) if any(x in element for x in list1)]

How can I just get a list of booleans?


Solution

  • To find only full word matches, you should match them to each string from list2 split by space to make a word array:

    print([any(x in element.split(' ') for x in list1) for element in list2]) 
    

    Test:

    list1 = ['foo', 'baz', 'bat', 'w']
    list2 = ['foo word word word', 'word baz word word', 'word word word word', 'word word bat word']
    

    results are:
    [True, True, False, True]
    which is the expected result.