Dmitry
Dmitry

Reputation: 14632

Is it possible to filter list of substrings by another list of strings in Python?

To filter list of strings by another list of strings in Python we can use the following code:

result = [x for x in strings1 if x in strings2]

But how can we filter list of substrings by another list of strings? For example:

substrings = ['a', 'b', 'c']
strings = ['_b_', '_c_', '_d_']

Result should be:

result = ['b', 'c']

Upvotes: 2

Views: 2600

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48090

Elegant way to achieve this is via using any with a list comprehension as:

>>> substrings = ['a', 'b', 'c']
>>> my_strings = ['_b_', '_c_', '_d_']

>>> [s for s in substrings if any(s in i for i in my_strings)]
['b', 'c']

Here any will return True if any of string in substrings is present as substring in my_strings. As soon as it finds the match, it will short-circuit the iteration (without checking for other matches) and will return the result as True. Due to the short-circuiting property of any, it won't make the unnecessary iteration across the entire list, resulting in better performance.

Upvotes: 3

Dekel
Dekel

Reputation: 62616

You can use something like that:

[x for x in substrings if [y for y in strings if x in y]]


In [1]: substrings = ['a', 'b', 'c']

In [2]: strings = ['_b_', '_c_', '_d_']

In [3]: [x for x in substrings if [y for y in strings if x in y]]
Out[3]: ['b', 'c']

Upvotes: 5

Related Questions