Table of Contents

问题

在看 collections.OrderedDict 的源码时,对于它如何构造有序的结构这一部分不是很理解,代码如下:

class OrderedDict(dict):
'Dictionary that remembers insertion order'
# 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]. def __init__(*args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary. '''
if not args:
raise TypeError("descriptor '__init__' of 'OrderedDict' object "
"needs an argument")
self = args[0]
args = args[1:]
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
return dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, _ = self.__map.pop(key)
link_prev[1] = link_next # update link_prev[NEXT]
link_next[0] = link_prev # update link_next[PREV] def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
root = self.__root
curr = root[1] # start at the first node
while curr is not root:
yield curr[2] # yield the curr[KEY]
curr = curr[1] # move to next node def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
root = self.__root
curr = root[0] # start at the last node
while curr is not root:
yield curr[2] # yield the curr[KEY]
curr = curr[0] # move to previous node def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
dict.clear(self)

主要是对于初始化里和set方法里的做法不清楚, wtf doing here…:

            self.__root = root = []                     # sentinel node
root[:] = [root, root, None]
self.__map = {}
# 和
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]

后来在网上提问并且自己查询了相关资料后明白这是个带哨兵的双向链表的实现,关于双向链表的知识自己补了下,可以参见这里这里

然而对于它为什么要这样实现我还不是很清楚,留待以后继续探究。

这里 是我在v2ex上关于这个问题的提问。

python双向链表的疑问(Question)的更多相关文章

  1. python双向链表的实现

    python双向链表和单链表类似,只不过是增加了一个指向前面一个元素的指针,下面的代码实例了python双向链表的方法 示意图: python双向链表实现代码: # -*- coding: utf-8 ...

  2. Python 双向链表

    操作 is_empty() 链表是否为空 length() 链表长度 travel() 遍历链表 add(item) 链表头部添加 append(item) 链表尾部添加 insert(pos, it ...

  3. Python学习二|Python的一些疑问

    最近写了一点Python代码,作为一个java程序员,面对Python这么便捷的语言不禁有点激动.不过呢,有时候也会遇到一些无法理解的东西. 例如: er = [[1,2,3], [4,5,6], [ ...

  4. Python multiprocessing相关疑问

    1. multiprocessing 和 threading有什么区别? threading module并没有真正利用多核.而multiprocessing 利用subprocess避开了pytho ...

  5. Python 双向链表 快速排序

    1.创建链表: from random import randint class DLinkedNode(object): def __init__(self, data=None, pre=None ...

  6. How to Access MySQL with Python Version 3.4

    http://askubuntu.com/questions/630728/how-to-access-mysql-with-python-version-3-4 How to Access MySQ ...

  7. Python学习之编程基础

    学习Python之前首先我们要了解Python是什么? question 1:Python是什么? answer:Python是一门编程语言.(什么是编程语言?) 语言:语言是不同个体之间沟通的介质. ...

  8. 怎么在windows上安装 ansible How to install ansible to my python at Windows

    答案是不能再window上安装,答案如下: It's back! Take the 2018 Developer Survey today » Join Stack Overflow to learn ...

  9. python为前端提供API

    作为一名前端来学习后端语言,有难度啊.这里把第一次尝试的过程做个记录 1.网上看到Python给前端提供API可以使用python的flaskweb框架 #py文件 import json from ...

随机推荐

  1. sql 删除字段 出错

    1. 删除字段:   ALTER TABLE TALE_NAME DROP COLUMN nn;   2.报错: 消息 5074,级别 16,状态 1,第 1 行对象'DF__WorkOrder__I ...

  2. springBoot 定时器任务

    1.新建一个计划任务类(只能和主类平级或在主类的下级) import java.text.SimpleDateFormat; import java.util.Date; import org.slf ...

  3. input和textarea修改placeholder颜色和字号

    方式1因为每个浏览器的CSS选择器都有所差异,所以需要针对每个浏览器做单独的设定(可以在冒号前面写input和textarea).::-webkit-input-placeholder { /* We ...

  4. meterpreter > sysinfo

    meterpreter > sysinfoComputer : test-VCS86VROS : Windows XP (Build 2600).Architecture : x86System ...

  5. 测试MS题

    购物车测试点:  1.界面测试        界面布局.排版是否合理:文字是否显示清晰:不同卖家的商品是否区分明显. 2.功能测试 未登录时: 将商品加入购物车,页面跳转到登录页面,登录成功后购物车数 ...

  6. 【BZOJ4540】 [HNOI2016] 序列(莫队)

    点此看题面 大致题意: 求出一个序列的一段区间中所有子序列最小值之和. 莫队 这道题其实是一道莫队题. 但是需要大量的预处理. 预处理 先考虑预处理两个数组\(lst_i\)和\(nxt_i\),分别 ...

  7. Being a Good Boy in Spring Festival(博弈)

    Being a Good Boy in Spring Festival Problem Description一年在外 父母时刻牵挂春节回家 你能做几天好孩子吗寒假里尝试做做下面的事情吧 陪妈妈逛一次 ...

  8. CentOS系统下安装Redis

    1. 安装C语言环境 yum install gcc-c++ 2.下载Redis安装包 http://download.redis.io/releases/redis-3.2.9.tar.gz 3.解 ...

  9. Scanner和 Random类,控制语句的例题,商品管理(直接赋值)

    Scanner类的使用: import java.util.Scanner; class Demo02 { public static void main(String[] args) { //1.导 ...

  10. HTML第四章:初始css

    CSS样式:                 一.为什么要使用CSS;可以让页面更美观.有利于开发速度.                 二.什么是CSS:全称cascading style shee ...