You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python识别字典列表中重复term值并移除对应条目的方法

字典列表重复term识别与过滤方案

完整实现代码

1. 基于标准库collections.Counter的Pythonic写法(推荐)

from collections import Counter

# 示例输入
terms_dict = [{'term': 'potato', 'cui': '123AB'}, {'term': 'carrot', 'cui': '222AB'}, {'term': 'potato', 'cui': '456AB'}]

# 统计所有term的出现频次
term_counts = Counter(item['term'] for item in terms_dict)

# 筛选重复term列表
repeated_terms = [term for term, cnt in term_counts.items() if cnt > 1]
# 过滤得到仅含唯一term的新字典列表
new_terms_dict = [item for item in terms_dict if term_counts[item['term']] == 1]

运行结果验证:

print(repeated_terms)
# 输出:['potato']
print(new_terms_dict)
# 输出:[{'term': 'carrot', 'cui': '222AB'}]

2. 无依赖原生字典实现

如果不想导入额外模块,可使用原生字典实现频次统计,后续筛选逻辑完全一致:

term_counts = {}
for item in terms_dict:
    term = item['term']
    term_counts[term] = term_counts.get(term, 0) + 1

repeated_terms = [term for term, cnt in term_counts.items() if cnt > 1]
new_terms_dict = [item for item in terms_dict if term_counts[item['term']] == 1]

两种方案时间复杂度均为O(n),仅需遍历原列表两次,性能优异且写法简洁。

内容的提问来源于stack exchange,提问作者blah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 09:54:00