2

I have the list like

l = ['dd','rr','abcde']

l2 = ['ddf','fdfd','123']

I want one function which return true if any of the value from l exist in l2.

Now that can be partial matching as well. i mean that string should present in l2

EDIT:

The output should be either true of false

Like in my example it should return true because dd is matching with ddf

Martin Paljak
  • 4,119
  • 18
  • 20
user2294401
  • 377
  • 2
  • 6
  • 14

3 Answers3

5

This returns True if any value from l is a substring of any value in l2:

any(l_value in l2_value for l_value in l for l2_value in l2)
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
1

Nested loops:

print any(sub in full for sub in l for full in l2)

Efficient nested loops

from itertools import product
print any(sub in full for sub, full in product(l, l2))

No loops:

import re
print re.match('|'.join(l), ' '.join(l2))
georg
  • 211,518
  • 52
  • 313
  • 390
0
def match():
   for e in l:
      for e2 in l2:
          if e in e2:
              return True
   else:
       return False

This will include the partial matches.

UPDATE: Using list comprehension:

[re.search(x,",".join(l2)) for x in l if re.search(x,",".join(l2)) is not None] and 'True' or 'False'
jamylak
  • 128,818
  • 30
  • 231
  • 230
thavan
  • 2,409
  • 24
  • 32