Home > OS >  Python - remove elements from array if element contains a partial match with elements in another arr
Python - remove elements from array if element contains a partial match with elements in another arr

Time:01-25

I'm looking for a way to filter all elements in an array if the element contains a substring that occurs in another filter-array. Below is an example:

target = ["one", "two", "three", "four", "five"]
filter = ["ree","wo"]

The following snippet works if the substrings array is a string and not an array

filter = "wo"
filtered_target = [string for string in target if filter in string]

However, I want it to remove all elements from the target array that contain substrings provided in the filter array. How could I approach this elegantly?

CodePudding user response:

You can leverage the any function -

target = ["one", "two", "three", "four", "five"]
filters = ["ree","wo"]

filterd_list = [s for s in target if not any(f in s for f in filters)]

this would remove all strings from target which have one of the filters as a substring, output -

['one', 'four', 'five']
  •  Tags:  
  • Related