【问题标题】:Unhashable type, removing duplicates from a collection but keep the entry orderUnhashable 类型,从集合中删除重复项但保持条目顺序
【发布时间】:2019-05-31 22:35:59
【问题描述】:

我希望根据键或键组合删除集合的所有重复项。

考虑下面的字典列表:

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

【问题讨论】:

    标签: python python-3.x dictionary hash


    【解决方案1】:

    使用OrderedDict,但对frozensets 的键进行哈希处理:

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

    【讨论】:

      猜你喜欢
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 2010-10-03
      • 2016-12-28
      相关资源
      最近更新 更多