How to compare two lists to keep matching substrings?

Viewed 1774

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?

3 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']

You can use any() to check if any element of your list B is in x:

A = ['dataFile1999', 'dataFile2000', 'dataFile2001', 'dataFile2002']

B = ['2000', '2001'] 

c = [x for x in A if any(k in x for k in B)]

print(c)

Output:

['dataFile2000', 'dataFile2001']

First, I would construct a set of the years for the O(1) lookup time.1

>>> A = ['dataFile1999', 'dataFile2000', 'dataFile2001', 'dataFile2002']
>>> B = ['2000', '2001']
>>> 
>>> years = set(B)

Now, keep only the elements of A that end with an element of years.

>>> [file for file in A if file[-4:] in years]
>>> ['dataFile2000', 'dataFile2001']

1 If you have very small lists (two elements certainly qualify) keep the lists. Sets have O(1) lookup but the hashing still introduces overhead.

Related