代码之家  ›  专栏  ›  技术社区  ›  Paul Nathan

询问关于python值的“is hashable”

  •  41
  • Paul Nathan  · 技术社区  · 14 年前

    我对任意听写感兴趣,并将其复制到一个新的听写中,一路改变它。

    我想做的一个变异是交换密钥和值。不幸的是,有些价值观本身就是主旨。但是,这会生成一个“unhashible type:'dict'”错误。我真的不介意把价值串起来,然后给它钥匙。但是,我希望能够做这样的事情:

    for key in olddict:
      if hashable(olddict[key]):
        newdict[olddict[key]] = key
      else
        newdict[str(olddict[key])] = key
    

    有干净的方法吗 包括捕获异常并分析“不可缓存类型”的消息字符串?

    4 回复  |  直到 8 年前
        1
  •  47
  •   Mark Byers    14 年前

    因为python 2.6,您可以使用抽象基类 collections.Hashable :

    import collections
    >>> isinstance({}, collections.Hashable)
    False
    >> isinstance(0, collections.Hashable)
    True
    

    在文档中还简要介绍了这种方法 __hash__ .

    这样做不仅意味着类的实例将 TypeError 当程序尝试检索其哈希值时,但在检查时也会正确地将其标识为不可缓存 isinstance(obj, collections.Hashable) (不同于定义自己的类 __hash__() 明确提出 类型错误 )

        2
  •  15
  •   Ned Batchelder    14 年前
    def hashable(v):
        """Determine whether `v` can be hashed."""
        try:
            hash(v)
        except TypeError:
            return False
        return True
    
        3
  •  4
  •   Chandler    14 年前

    所有内置python对象都有一个 .__hash__() 方法。你可以查一下。

    olddict = {"a":1, "b":{"test":"dict"}, "c":"string", "d":["list"] }
    
    for key in olddict:
       if(olddict[key].__hash__):
          print str(olddict[key]) + " is hashable"
       else: 
          print str(olddict[key]) + " is NOT hashable"
    

    输出

    1 is hashable
    string is hashable
    {'test': 'dict'} is NOT hashable
    ['list'] is NOT hashable
    
        4
  •  1
  •   dansalmo    11 年前

    为什么不用鸭子打字?

    for key in olddict:
       try:
           newdict[olddict[key]] = key
       except TypeError:
           newdict[str(olddict[key])] = key