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

如何按条件移除字典列表重复项:保留同场景下最长title项

解决方案

实现思路

  1. 按situation字段对字典列表分组,将同场景的字典归为一组;
  2. 对每个场景组,筛选出title字符串长度最长的字典——最长的title必然包含同组内较短的、存在包含关系的title,保留它即可满足需求。

代码实现

list_dict = [
    {'title':'abc defg hij', 'situation':'other'},
    {'title':'c defg', 'situation':'other'},
    {'title':'defg hij', 'situation':'other'},
    {'title':'defg hij', 'situation':'deleted'}
]

# 按situation分组
grouped = {}
for item in list_dict:
    sit = item['situation']
    if sit not in grouped:
        grouped[sit] = []
    grouped[sit].append(item)

# 筛选每个组中title最长的字典
result = []
for group in grouped.values():
    longest_item = max(group, key=lambda x: len(x['title']))
    result.append(longest_item)

print(result)

输出结果

[{'title':'abc defg hij', 'situation':'other'},
 {'title':'defg hij', 'situation':'deleted'}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:22:47