如何从字典列表中提取基于height键的唯一字典?
字典列表按内容去重实现方案
原始数据
data_list = [ {"AB":1.23, 'height':60.0}, {"AB":1.23, 'height':61.0}, {"AB":1.23, 'height':60.0}, {"AC":2.60, 'height':60.0}, {"AC":2.60, 'height':62.0}, {"AC":2.60, 'height':60.0}, ]
需求
保留所有内容唯一的字典(即键值对完全相同的字典仅保留一次),得到如下结果:
[ {"AB":1.23, 'height':60.0}, {"AB":1.23, 'height':61.0}, {"AC":2.60, 'height':60.0}, {"AC":2.60, 'height':62.0}, ]
你的尝试问题分析
你嵌套循环的逻辑完全偏离了去重目标:只是比较不同索引字典的height值是否不同就添加元素,导致大量重复元素被加入,根本没实现去重效果。
正确实现方法
因为字典是不可哈希类型,不能直接用集合去重,我们可以把字典转换为可哈希的元组(对键值对排序,确保内容相同的字典转换后一致),再利用集合记录已出现的内容。
方法1:基础遍历实现
data_list = [ {"AB":1.23, 'height':60.0}, {"AB":1.23, 'height':61.0}, {"AB":1.23, 'height':60.0}, {"AC":2.60, 'height':60.0}, {"AC":2.60, 'height':62.0}, {"AC":2.60, 'height':60.0}, ] seen = set() new_data_list = [] for d in data_list: # 将字典的键值对排序后转成元组,保证内容相同的字典生成相同的元组 tuple_key = tuple(sorted(d.items())) if tuple_key not in seen: seen.add(tuple_key) new_data_list.append(d) print(new_data_list)
方法2:简洁的列表推导式
data_list = [ {"AB":1.23, 'height':60.0}, {"AB":1.23, 'height':61.0}, {"AB":1.23, 'height':60.0}, {"AC":2.60, 'height':60.0}, {"AC":2.60, 'height':62.0}, {"AC":2.60, 'height':60.0}, ] seen = set() new_data_list = [d for d in data_list if not (tuple(sorted(d.items())) in seen or seen.add(tuple(sorted(d.items()))))] print(new_data_list)
运行结果
两种方法都会输出你需要的去重后列表:
[ {'AB': 1.23, 'height': 60.0}, {'AB': 1.23, 'height': 61.0}, {'AC': 2.6, 'height': 60.0}, {'AC': 2.6, 'height': 62.0} ]
内容的提问来源于stack exchange,提问作者orez
相关产品推荐
相关产品推荐

