1

我有一个包含多个元素的列表,我想删除重复的,这是一个列表示例:

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'}]

我试图使用函数集,但我有一个错误,它说列表是不可散列的,有人知道如何删除重复项吗?

4

1 回答 1

4

您仍然可以使用 aset()但您需要将每个列表变成一个元组;在这里,我们使用键和值的排序元组来准确查找重复项:

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'}]
于 2013-04-23T15:31:15.640 回答