Python如何删除嵌套列表中属于其他元素子序列的所有元素?
嵌套列表子序列过滤实现
需求说明
给定如下嵌套列表:
[['rest'],['look'],['rest','look'],['resting','look'],['apple','mango'],['apple','man'],['apple','banana','mango'],['rest','resting','look','looked','it','spit']]
需要删除所有是其他元素子序列的子列表,规则如下:
- 元素
['rest']、['look']存在于['rest','look']和长rest列表中,属于子序列,删除 - 元素
['rest','look']是长rest列表的子序列,删除 - 元素
['resting','look']是长rest列表的子序列,删除 - 元素
['apple','mango']是['apple','banana','mango']的子序列,删除 - 元素
['apple','man']不属于其他任何元素的子序列,保留
最终输出为list类型,预期结果:
[['apple','man'],['apple','banana','mango'],['rest','resting','look','looked','it','spit']]
原有代码问题
原有代码存在两处核心错误:
- 逻辑偏离需求:仅判断单个字符串元素是否存在于其他列表,未判断整个子列表是否是另一个子列表的子序列
found变量未在循环中重置:首次匹配到相等元素后found永久为1,后续无元素被添加到结果,导致输出空列表
正确实现代码
首先实现子序列判断的辅助函数,再遍历所有候选列表检查是否需要保留:
def is_subsequence(a, b): """判断列表a是否是列表b的子序列""" if len(a) > len(b): return False a_ptr = b_ptr = 0 while a_ptr < len(a) and b_ptr < len(b): if a[a_ptr] == b[b_ptr]: a_ptr += 1 b_ptr += 1 return a_ptr == len(a) x = [['rest'],['look'],['rest','look'],['resting','look'],['apple','mango'],['apple','man'],['apple','banana','mango'],['rest', 'resting', 'look', 'looked', 'it', 'spit']] result = [] for candidate in x: is_sub_of_other = False # 检查当前候选是否是其他任意列表的子序列 for other in x: if candidate == other: continue if is_subsequence(candidate, other): is_sub_of_other = True break if not is_sub_of_other: result.append(candidate) print(result)
运行上述代码即可得到预期输出。
内容的提问来源于stack exchange,提问作者Rosaline Mcguirre
相关产品推荐
相关产品推荐

