如何按条件移除字典列表重复项:保留同场景下最长title项
解决方案
实现思路
- 按
situation字段对字典列表分组,将同场景的字典归为一组; - 对每个场景组,筛选出
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
相关产品推荐
相关产品推荐

