Reputation: 14632
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
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
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