Python如何从包含dict的嵌套列表中高效生成唯一列表
高效去重方案
可以通过将不可哈希的字典结构转换为可哈希类型,结合集合做去重,整体时间复杂度为O(n),比嵌套循环逐个比对的效率高很多。
方法1:JSON序列化方案(兼容性最好)
适用所有场景,哪怕字典键的顺序不同、子列表长度变化也可以正常识别重复项,仅需要导入Python内置的json标准库:
import json original_list = [ [{'port': 18, 'module': 1, 'policy_group': 'policy_group1'}], [{'port': 10, 'module': 1, 'policy_group': 'policy_group2'}], [{'port': 10, 'module': 1, 'policy_group': 'policy_group2'}] ] seen = set() unique_list = [] for sub_list in original_list: # sort_keys参数强制按键排序序列化,避免同内容不同键顺序被判定为不同项 hash_key = json.dumps(sub_list, sort_keys=True) if hash_key not in seen: seen.add(hash_key) unique_list.append(sub_list) # 输出结果即为目标去重列表 print(unique_list)
方法2:元组转换方案(无额外依赖)
如果你确定所有子列表都仅包含1个字典,且字典的键顺序完全统一,可以不用导入任何依赖,直接转元组处理:
seen = set() unique_list = [] for sub_list in original_list: hash_key = tuple(sub_list[0].items()) if hash_key not in seen: seen.add(hash_key) unique_list.append(sub_list)
内容的提问来源于stack exchange,提问作者ovntatar
相关产品推荐
相关产品推荐

