Python如何移除列表中作为其他元素子串的短字符串元素
Python字符串列表冗余子串过滤实现
需求规则
- 优先保留列表内的长字符串元素
- 若某一字符串是列表中另一个更长字符串的子串,则删除该冗余短字符串
测试样例
- 输入:
List1 = ['this', 'is', 'to', 'ask', 'this question']
- 预期输出:
['is', 'to', 'ask', 'this question']
过滤说明:短字符串
this是更长字符串this question的子串,因此被移除;其余短字符串is/to/ask均不是其他更长元素的子串,因此保留。
实现代码
def filter_substring_redundancy(input_list): # 按字符串长度降序排序,优先处理长字符串 length_sorted = sorted(input_list, key=lambda x: len(x), reverse=True) kept_strings = [] for s in length_sorted: # 当前字符串不是任何已保留长串的子串时,才加入保留列表 if not any(s in kept for kept in kept_strings): kept_strings.append(s) # 按原列表的元素顺序返回结果,匹配常规使用的顺序预期 return [item for item in input_list if item in kept_strings] # 功能测试 if __name__ == "__main__": List1 = ['this', 'is', 'to', 'ask', 'this question'] List1 = filter_substring_redundancy(List1) print(List1) # 运行输出:['is', 'to', 'ask', 'this question']
逻辑说明
- 长字符串优先判定:先按长度降序排序,保证长字符串最先进入保留列表,避免短串先被保留导致长串被误过滤
- 子串校验:每遍历一个字符串,就和已保留的所有更长字符串做子串匹配,匹配命中说明是冗余串,直接跳过
- 顺序还原:最终结果按照元素在原列表中的出现顺序重排,不会打乱原有非冗余元素的相对位置
内容的提问来源于stack exchange,提问作者Sonali Bapte
相关产品推荐
相关产品推荐

