【问题标题】:How does Python's OrderedDict remember elements inserted?Python 的 OrderedDict 如何记住插入的元素?
【发布时间】:2016-02-18 07:35:42
【问题描述】:

Python 中的OrderedDict 如何记住所有元素的顺序?性能开销是多少?对于像实现LRU 这样的问题,我发现这非常强大并且实现起来非常简单,但是这里的性能增益是多少?它如何记住第一次插入的键的顺序?

它是否使用Dict()Double Linked List 来记住下图所示的键?如果您能用简单的语言传达您的信息,而不是分享某种研究论文,我将不胜感激。

【问题讨论】:

    标签: python dictionary collections ordereddictionary lru


    【解决方案1】:

    最好的一点是您可以查看OrderedDict 的源代码以更好地理解它。

    它实际上也是用纯python实现的!这意味着您可以复制、重新定义它,并且通常可以随意地对其进行变异,直到您理解它为止。

    它确实使用了双向链表,这是在源文件的文档字符串中指定的。掌握 how doubly linked lists work 并浏览源代码,您会很好地了解它的工作原理:

    # An inherited dict maps keys to values.
    # The inherited dict provides __getitem__, __len__, __contains__, and get.
    # The remaining methods are order-aware.
    # Big-O running times for all methods are the same as regular dictionaries.
    
    # The internal self.__map dict maps keys to links in a doubly linked list.
    # The circular doubly linked list starts and ends with a sentinel element.
    # The sentinel element never gets deleted (this simplifies the algorithm).
    # Each link is stored as a list of length three:  [PREV, NEXT, KEY].
    

    【讨论】:

    • 谢谢,这肯定很有帮助。
    • 你能否详细说明最后三行谈论sentinel element
    • 哨兵本质上是虚拟节点,用于标记链表的开始和结束以进行优化。他们有很多资源[123],这更多是理论上的方面。最后一个简单地表示每个节点的内容应该是什么。
    猜你喜欢
    • 2016-11-30
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2011-04-26
    • 2012-07-24
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多