3

任何人都可以提供一个关于如何通过将键散列到值并避免/处理python中的冲突来创建散列表的好教程吗?我在这里和那里看到了很多小代码,但我想知道是否有人可以帮助我。

基本上:

  • 创建表
  • 选择一个散列函数并将键散列到表中
  • 处理碰撞
  • 在所述表上执行查找
4

1 回答 1

3

您是否尝试过自定义对象以使用内置的dict类型?它是一个哈希表。要自定义散列,您需要做的就是确保您的关键对象是Hashable

class Foo(object)
    def __hash__(self)
         #return good (int) hash for a Foo

    def __eq__(self, other)
         #return true if self == other

    def __ne__(self, other)
         #return true if self != other

现在 Foo 可以成为 dict 的关键

d = {Foo(): "value1", Foo(): "value2"}
于 2012-08-20T20:53:45.393 回答