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 substri
Solution 1:
You can use something like that:
[x forxin substrings if [y foryin strings if x in y]]
In [1]: substrings = ['a', 'b', 'c']
In [2]: strings = ['_b_', '_c_', '_d_']
In [3]: [x forxin substrings if [y foryin strings if x in y]]
Out[3]: ['b', 'c']
Solution 2:
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 ifany(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.
Post a Comment for "Is It Possible To Filter List Of Substrings By Another List Of Strings In Python?"