Python-如果元素包含与另一个数组中的元素的部分匹配,则从数组中移除元素



我正在寻找一种方法来过滤数组中的所有元素,如果该元素包含另一个过滤器数组中出现的子字符串。下面是一个例子:

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

如果子字符串数组是字符串而不是数组,则以下代码段有效

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

但是,我希望它从目标数组中删除包含筛选器数组中提供的子字符串的所有元素。我怎么能优雅地处理这个问题呢?

您可以利用any函数-

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)]

这将从目标中删除所有字符串,其中一个过滤器作为子字符串,输出-

['one', 'four', 'five']

最新更新