代码之家  ›  专栏  ›  技术社区  ›  Tommy Herbert

Python字典是哈希表的一个例子吗?

  •  146
  • Tommy Herbert  · 技术社区  · 18 年前

    4 回复  |  直到 15 年前
        1
  •  283
  •   zvyn    11 年前

    是的,它是一个哈希映射或哈希表。您可以阅读Tim Peters编写的python dict实现的描述, here .

    >>> a = {}
    >>> b = ['some', 'list']
    >>> hash(b)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: list objects are unhashable
    >>> a[b] = 'some'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: list objects are unhashable
    

    你可以 read more about hash tables 或 check how it has been implemented in python why it is implemented that way

        2
  •  42
  •   Bob Stein    11 年前

    Python字典中必须有比哈希()上的表查找更多的内容。通过野蛮的实验,我发现了这个 散列冲突

    >>> hash(1.1)
    2040142438
    >>> hash(4504.1)
    2040142438
    

    但它并没有打破字典:

    >>> d = { 1.1: 'a', 4504.1: 'b' }
    >>> d[1.1]
    'a'
    >>> d[4504.1]
    'b'
    

    健全性检查:

    >>> for k,v in d.items(): print(hash(k))
    2040142438
    2040142438
    

    (顺便说一句,这在Python2.7.10中也是如此。在Python3.4.3和3.5.0中也是如此,在 hash(1.1) == hash(214748749.8) .)

        3
  •  22
  •   Aaron Hall    9 年前
        4
  •  8
  •   Jeremy Cantrell    18 年前

    要扩展nosklo的解释:

    a = {}
    b = ['some', 'list']
    a[b] = 'some' # this won't work
    a[tuple(b)] = 'some' # this will, same as a['some', 'list']