Compare strings of a list and a matrix in python

  list, matrix, python, python-3.x, string

I want to compare substrings of a matrix and strings of a list.

l1=['phone','bag','name','after']
l2=[['phoneedjf','jshph o n ejsh','pho ne'],
['ffaf terekdl','a hf ter','fd af t e rls'],
['name s', 'ram es','her na me is'],
['ba gg in g','ba g pa ck','b a g'],
['bo ok s','sksjbooksjfl','b o o k kfs ifh']]

And this my code:

l3=list()
l3=l2
    
import numpy.core.defchararray as np_f
new_data = np_f.replace(l3, ' ', '')
print(new_data)

new_data=list(new_data)

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

And the output of this code is:

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

Even I tried this code:

for i, value in enumerate(l3):
    print([any(x in element.split() for x in l3) for element in l1]) 

But the compiler return this error:

AttributeError: ‘list’ object has no attribute ‘split’

And my desire output should be like this:

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

As you see in the code, I have copied the matrix l2 into l3 and then deleted the spaces between characters in l3 to find the strings of the list in the substrings of the matrix and check them.
How I can solve this problem to have the expected output?

Thank you for your help.

Source: Python Questions

LEAVE A COMMENT