python双向链表的疑问(Question)
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)的更多相关文章
- python双向链表的实现
python双向链表和单链表类似,只不过是增加了一个指向前面一个元素的指针,下面的代码实例了python双向链表的方法 示意图: python双向链表实现代码: # -*- coding: utf-8 ...
- Python 双向链表
操作 is_empty() 链表是否为空 length() 链表长度 travel() 遍历链表 add(item) 链表头部添加 append(item) 链表尾部添加 insert(pos, it ...
- Python学习二|Python的一些疑问
最近写了一点Python代码,作为一个java程序员,面对Python这么便捷的语言不禁有点激动.不过呢,有时候也会遇到一些无法理解的东西. 例如: er = [[1,2,3], [4,5,6], [ ...
- Python multiprocessing相关疑问
1. multiprocessing 和 threading有什么区别? threading module并没有真正利用多核.而multiprocessing 利用subprocess避开了pytho ...
- Python 双向链表 快速排序
1.创建链表: from random import randint class DLinkedNode(object): def __init__(self, data=None, pre=None ...
- 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 ...
- Python学习之编程基础
学习Python之前首先我们要了解Python是什么? question 1:Python是什么? answer:Python是一门编程语言.(什么是编程语言?) 语言:语言是不同个体之间沟通的介质. ...
- 怎么在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 ...
- python为前端提供API
作为一名前端来学习后端语言,有难度啊.这里把第一次尝试的过程做个记录 1.网上看到Python给前端提供API可以使用python的flaskweb框架 #py文件 import json from ...
随机推荐
- MATLAB之数学建模:深圳市生活垃圾处理社会总成本分析
MATLAB之数学建模:深圳市生活垃圾处理社会总成本分析 注:MATLAB版本--2016a,作图分析部分见<MATLAB之折线图.柱状图.饼图以及常用绘图技巧> 一.现状模式下的模型 % ...
- Java Web中web.xml文件简单介绍
参考博客: https://www.cnblogs.com/Y-oung/p/8401549.html 1.XML 声明和根元素 <?xml version="1.0" en ...
- lintcode五道题
1.二叉树的最大深度 最大深度为根节点到最远叶子节点的距离为最大深度,于是可以先找到根节点到叶子节点最大的距离,过程就可以分为左子树 和右子树分别进行来求左.右子树的最大深度lh=height(roo ...
- Python Visual Studio 2015
对于一直是C#开发的我来说,上Python是老早就想的事情了. 上次有个项目开始做就说要用Python,后来因为不太熟练就给推掉了.现在终于还是有机会开始下Python之旅. 因为是在Visual S ...
- cms-静态化组件
1.要让我们的网站性能更好,那么有的东西是需要做静态化的.做静态化步骤: 1.1在web.xml中配置监听器 1.2.创建一个bean用来实现静态化 web.xml <?xml version= ...
- java Vamei快速教程05 实施接口
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 在封装与接口中,private关键字封装了对象的内部成员.经过封装,产品隐藏了内部 ...
- cesium加载shp格式数据
方法一: shp格式转换为GeoJson格式并加载 首先注意shp的坐标系,要转换为WGS84,使用arcgis或QGIS 工具:http://mapshaper.org/: 注意:export时,输 ...
- <已解决> Eclipse启动失败
参考:http://stackoverflow.com/questions/15404964/starting-eclipse-results-in-failed-to-create-java-vir ...
- Java jvm 内存回收机制
http://blog.csdn.net/yaerfeng/article/details/51291903 在Java中,它的内存管理包括两方面:内存分配(创建Java对象的时候)和内存回收,这两方 ...
- python_43_移动文件指针补充
#移动文件指针补充 ''' 文件对象.seek((offset,where)) offset:移动的偏移量,单位为字节.等于正数时向文件尾方向移动,等于负数时向文件头方向移动文件指针 where:指针 ...