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.
CodePudding user response:
def compare_lists(l1, l2):
l2 = [list(map(lambda x: x.replace(' ', ''), l)) for l in l2]
out = list()
for ele in l2:
temp = []
for l in ele:
temp.append(any([x in l for x in l1]))
out.append(temp)
return out
This function fist removes the spaces in all the strings.
Thereafter it loops over each element in the list. For one element it checks if one of the words from list is in one of the strings. This create a 4x1 array with False or True. The sum of an array with False and True is larger than zero when at least one element is True. After that it appends 1 or zero to the output list.
Hope this helps, please ask if it is not clear how the function works.