Check if any element of a list is in a matrix?

I have a small list:

list2 = ['hi', 'ma', 'ja']

and I have a matrix too. for example:

matrix2 = ([['high','h ight','hi ght','h i g ht'],
       ['man','ma n','ma th','mat h'],
       ['ja cket','j a ck et','jack et','ja m']
       ['ma nkind','jack',' hi ','hi'])

And I need to determine if any of the elements of l ist2 of this array are not in the matrix2. I try to use np.isin() :

np.isin(matrix2,list2) 

But this code only shows if there is the elements in the matrix or not completely. But I need this output:

output = ([[False, False, True, False],
       [False, True, True, False],
       [True, False, False, True]
       [True, False, True, False])])

As you can see in the output, the spaces are important too. For example, ‘hi’ without space before and after it is not something that I want it. I need the list by considering spaces between the set of characters.

Could anyone help me to solve this problem?

Answer

You have to loop over the matrix and then over each row of the matrix. Then you have a single string that you have to split to get the individual parts. Now you can check if any of this parts is in list2.

list2 = [‘hi’, ‘ma’, ‘ja’]

matrix2 = [['high','h ight','hi ght','h i g ht'],
            ['man','ma n','ma th','mat h'],
            ['ja cket','j a ck et','jack et','ja m'],
            ['ma nkind','jack',' hi ','hi']]

output = []
for row in matrix2:
    new_row = [any(value in list2 for value in element.split()) for element in row]
    output.append(new_row)
print(output)

The result is

[[False, False, True, False], 
 [False, True, True, False], 
 [True, False, False, True], 
 [True, False, True, True]]

A minor change that takes the additional constraint of an existing space into account.

output = []
for row in matrix2:
    new_row = [any(value in list2 and ' ' in element for value in element.split()) for element in row]
    output.append(new_row)
print(output)

This will give you

[[False, False, True, False],
 [False, True, True, False],
 [True, False, False, True],
 [True, False, True, False]]