2

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']
1
  • with a simple list comprehension: [i for i in substrings for j in strings if i in j] Commented Sep 3, 2017 at 23:55

2 Answers 2

5

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Was trying to use this in one of my function, but it gives TypeError: a bytes-like object is required, not 'str' . Could you suggest a solution
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.