Python如何提取不包含另一列表指定子串的列表元素
正确实现方案
原代码问题说明
- 子串判断方向错误:你需要判断禁用子串是否包含在源列表元素中,而非源列表元素是否包含在禁用子串中,原写法
x not in y逻辑完全颠倒,应为y not in x - 逻辑量词使用错误:需求是「元素不能包含任意禁用子串」,即所有禁用子串都不可以出现在元素中,应当使用
all而非any
基础实现(列表推导式)
exclude_list = ['not_use', 'dont_use'] feature_list = ['good_use', 'very_good_use', 'hey_not_use', 'hey_dont_use'] desired_list = ['good_use', 'very_good_use'] ret_list = [x for x in feature_list if all(sub not in x for sub in exclude_list)] print(ret_list) assert set(ret_list) == set(desired_list), 'list are not identical'
高性能实现(适合大数量级场景)
如果禁用子串数量多、源列表长度大,可以用正则预编译的方式减少重复遍历开销:
import re exclude_list = ['not_use', 'dont_use'] feature_list = ['good_use', 'very_good_use', 'hey_not_use', 'hey_dont_use'] desired_list = ['good_use', 'very_good_use'] # 自动转义禁用子串中的特殊字符,预编译正则模式 exclude_pattern = re.compile('|'.join(re.escape(sub) for sub in exclude_list)) # 未匹配到任何禁用子串的元素才保留 ret_list = [x for x in feature_list if not exclude_pattern.search(x)] print(ret_list) assert set(ret_list) == set(desired_list), 'list are not identical'
内容的提问来源于stack exchange,提问作者Yehoshaphat Schellekens
相关产品推荐
相关产品推荐

