Skip to main content
 首页 » 编程设计

python之不可散列类型,从集合中删除重复项但保留条目顺序

2024年09月03日28dflying

我正在寻找基于键或键组合删除集合的所有重复项。

考虑下面的字典列表:

c = [ {'a':1, 'b':2}, {'a':1, 'b':3}, {'a':1, 'b':2}, {'a':2, 'z':4}] 

所需的输出将根据键删除重复项。对于 a 删除重复输出:

[ {'a':1, 'b':2}, {'a':2, 'z':4}] 

对于可哈希集合,以下代码对我有用:

def dups(seq): 
    seen = [] 
    for item in seq: 
        if item not in seen: 
            seen.append(item) 
    return seen 

请您参考如下方法:

使用 OrderedDict,但在键的 frozenset 上散列:

from collections import OrderedDict 
 
o = OrderedDict((frozenset(d), d) for d in reversed(c)) 
uniq = list(o.values())[::-1] 
 
print(uniq) 
# [{'a': 1, 'b': 2}, {'a': 2, 'z': 4}] 

我在将 c 传递给 OrderedDict 之前反转它,然后反转我提取的值。这确保我删除重复项,保留第一个。


您可以通过散列键的卡住集来将卡住集扩展到现有代码。使用 set 进行高效查找。

def dups(seq): 
    seen = set() 
    for item in seq: 
        hashval = frozenset(item) 
        if hashval not in seen: 
            seen.add(hashval) 
            yield item 
 
uniq = list(dups(c)) 
print(uniq) 
# [{'a': 1, 'b': 2}, {'a': 2, 'z': 4}]