Python如何过滤包含另一列表任意子串的列表元素
实现方案
基础列表推导实现
直接使用Python内置的all()函数配合列表推导即可实现需求,代码如下:
a = ["table_a", "table_b", "table_c", "xyz", "abc"] b = ["x", "c"] c = [item for item in a if all(sub_str not in item for sub_str in b)] print(c) # 输出: ['table_a', 'table_b']
逻辑说明:
- 遍历列表
a中的每一个元素item - 对每个
item,检查列表b中所有子串是否都不存在于item中:只要有任意一个b的子串出现在item里,all()就会返回False,该item就会被排除 - 最终保留的元素完全符合你的过滤规则
高性能扩展方案(适用于大数量级场景)
如果a和b的长度都很大,遍历判断的性能会偏低,可以使用正则表达式预编译的方式优化:
import re a = ["table_a", "table_b", "table_c", "xyz", "abc"] b = ["x", "c"] # 先转义b中的特殊正则字符,再合并为匹配模式 pattern = re.compile("|".join(map(re.escape, b))) c = [item for item in a if not pattern.search(item)] print(c) # 输出: ['table_a', 'table_b']
内容的提问来源于stack exchange,提问作者CodingInCircles
相关产品推荐
相关产品推荐

