I'm new to python so apologies if its a silly question.
I have two lists
L1=['marvel','audi','mercedez','honda']
and
L2=['marvel comics','bmw','mercedez benz','audi']
.
I want to extract matching elements which contains in list L2
matched with list L1
. So what I done :
for i in L1:
for j in L2:
if j in i:
print (j)
output is ['audi']
But, I also wants to return elements if its also consist any word match like mercedez
in mercedez benz
and marvel
in marvel comics
. so final output would be:
j=['audi','mercedez benz','marvel comics']
If you would like to use
regular expressions
then you can do:a performant approach would be to build a "flat" dictionary with each word as key and the relevant group of words as value.
which is:
now scan the first list and issue element if in dictionary:
result:
once the dictionary is built, you can scan large lists with high performance (
O(1)
lookup)Using list comprehension:
Make some changes in your code
This is one approach using
str.startswith
Ex:
Output:
Using
in
Ex:
I think what you really want here is the elements of
L2
that contain any elements inL1
. So simply replaceif j in i
withif i in j
:This outputs: