【问题标题】:Python - remove elements from array if element contains a partial match with elements in another arrayPython - 如果元素包含与另一个数组中的元素的部分匹配,则从数组中删除元素
【发布时间】:2022-01-24 16:48:01
【问题描述】:

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

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

如果子字符串数组是字符串而不是数组,则以下 sn-p 有效

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

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

【问题讨论】:

    标签: python arrays


    【解决方案1】:

    您可以利用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']
    

    【讨论】:

    • 谢谢杰!我正在查看任何功能,但无法在一行代码中使用它,这非常有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 2023-01-26
    • 2021-01-28
    • 1970-01-01
    相关资源
    最近更新 更多