Python通过匹配外部列表值筛选多层嵌套列表的实现方法
大数据量适配实现方案
首先做前置优化:将外部姓名列表List_Outside转换为集合类型,将姓名匹配的时间复杂度从O(n)降低到O(1),处理7500+条数据时性能提升明显。
带索引的for循环实现代码如下:
# 预处理:外部姓名转集合提升查找效率 outside_set = set(List_Outside) List_A_2 = [] # 带索引遍历List_A for idx in range(len(List_A)): # 如果你使用的是链表结构,将下行替换为 current_node = List_A.nodeat(idx).value 即可 current_node = List_A[idx] # 取出当前子项内的姓名字段(索引为3的位置) inner_name_list = current_node[3] # 检查是否存在匹配的姓名 has_match = False for name in inner_name_list: if name in outside_set: has_match = True break if has_match: List_A_2.append(current_node)
运行上述代码后得到的List_A_2就是符合要求的过滤结果,和你给出的预期输出完全一致。
内容的提问来源于stack exchange,提问作者Ricardo Gomez
相关产品推荐
相关产品推荐

