1

Example:

L1=['cat', 'dog', 'fish', 'bird', 'rabbit', 'horse']

L2=[('cat', 'a', 'b', 'c'), ('cat', 'c', 'd', 'e'), ('cat', 'e', 'f', 'g'), ('fish', 'x', 'y', 'z'), ('dog', 'w', 'x', 'y'), ('dog', 'z', 'y', 'x'), ('horse', '1', '2', '3'), ('monkey', 'a', 'b', 'c'), ('kitten', 'h', 'i', 'j'), ('bird', '4', '5', '6')]

I am trying to search the strings in L1 in L2, so that if the string in L1 is present in any part of L2, the whole entry from L2 "('cat, a, b, c')" is appended to a new list. I also thought that maybe removing the entries that do not have any part of a string from L1 would work. I tried:

def searcher(L1, L2):
    common = []
    for x in L1:
        if re.search(x, L2):
            common.append(L2)

    return common

but that didnt work. The actual list I am using is much longer, so an efficient code would really help me out.

Thanks!

marsx
  • 715
  • 4
  • 10
  • 15

2 Answers2

5

Try

s = set(L1)
new_list = [a for a in L2 if any(b in s for b in a)]
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
0

Maybe

s = set(L1)
new_list = [a for a in L2 if s.intersection([w.strip() for w in set(a.split(","))])]
Qnan
  • 3,714
  • 18
  • 15