Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two lists to keep matching substrings?

As best I can describe it, I have two lists of strings and I want to return all results from list A that contain any of the strings in list B. Here are details:

A = ['dataFile1999', 'dataFile2000', 'dataFile2001', 'dataFile2002']
B = ['2000', '2001']

How do I return

C = ['dataFile2000', 'dataFile2001']?

I've been looking into list comprehensions, doing something like below

C=[x for x in A if B in A] 

but I can't seem to make it work. Am I on the right track?

like image 361
White Fish Avatar asked Dec 23 '22 03:12

White Fish


1 Answers

You were close, use any:

C=[x for x in A if any(b in x for b in B)]

More detailed:

A = ['dataFile1999', 'dataFile2000', 'dataFile2001', 'dataFile2002']
B = ['2000', '2001']

C = [x for x in A if any(b in x for b in B)]

print(C)

Output

['dataFile2000', 'dataFile2001']
like image 160
Dani Mesejo Avatar answered Jan 15 '23 02:01

Dani Mesejo