简体   繁体   中英

How to check of the existence of any value in the list in python

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

如果l中的任何值是l2中任何值的子字符串,则返回True

any(l_value in l2_value for l_value in l for l2_value in l2)

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))
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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM