我有一个包含多个元素的列表,我想删除重复的,这是一个列表示例:
list = [{'status': 'OK', 'mid': '6639'}, {'status': 'OK', 'mid': '6639'}, {'status': 'OK', 'mid': '6640'}, {'status': 'OK', 'mid': '6640'}, {'status': 'OK', 'mid': '6641'}, {'status': 'OK', 'mid': '6641'}, {'status': 'OK', 'mid': '6642'}, {'status': 'OK', 'mid': '6643'}]
我试过使用函数集但是我有一个错误,它说列表是不可用的,是否有人知道如何删除重复?
答案 0 :(得分:4)
你仍然可以使用set()
但你需要将每个列表变成一个元组;这里我们使用键和值的排序元组来准确地找到重复项:
set(tuple(sorted(el.items())) for el in somelist)
为了使列表保持正常并保持字典完整,您可以使用:
seen = set()
seen_add = seen.add
[x for x in somelist if tuple(sorted(x.items())) not in seen and not seen_add(tuple(sorted(x.items())))]
后者的演示:
>>> seen = set()
>>> seen_add = seen.add
>>> [x for x in somelist if tuple(sorted(x.items())) not in seen and not seen_add(tuple(sorted(x.items())))]
[{'status': 'OK', 'mid': '6639'}, {'status': 'OK', 'mid': '6640'}, {'status': 'OK', 'mid': '6641'}, {'status': 'OK', 'mid': '6642'}, {'status': 'OK', 'mid': '6643'}]