zoukankan      html  css  js  c++  java
  • [Dynamic Language] Python OrderedDict 保证按插入的顺序迭代输出

    Python 2.7 中的OrderedDict 可以在迭代字典Items的时候保证按每项插入的顺序输出。
    当删除某项再用同样的key写入时,此项排在迭代的最后,同样是插入顺序排列的。
    可以用popitem的last=True/False来控制pop进返回最近插入的还是最早插入的,实际上就是维护了一个双向链表。

    abeen@localhost:~$ python2.7
    Python 2.7.2 (default, Oct 9 2011, 20:20:38)
    [GCC 4.4.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from collections import OrderedDict
    >>> d = OrderedDict([('one',1), ('tow', 2), ('three', 3)])
    >>> d.items()
    [('one', 1), ('tow', 2), ('three', 3)]
    >>> d['tow'] = 4
    >>> d.items()
    [('one', 1), ('tow', 4), ('three', 3)]
    >>> d['tow']
    4
    >>> d.items()
    [('one', 1), ('two', 4), ('three', 3)]
    >>> del d['two']
    >>> d.items()
    [('one', 1), ('three', 3)]
    >>> d['two'] = 4
    >>> d.items()
    [('one', 1), ('three', 3), ('two', 4)]
    >>>

    控制pop返回

    >>> d = OrderedDict([(x,0) for x in range(10)])
    >>> d.items()
    [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0)]
    >>> d.popitem()
    (9, 0)
    >>> d.popitem()
    (8, 0)
    >>> d.items()
    [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0)]
    >>> d.popitem(last=True)
    (7, 0)
    >>> d.popitem(last=True)
    (6, 0)
    >>> d.items()
    [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0)]
    >>> d.popitem(last=False)
    (0, 0)
    >>> d.popitem(last=False)
    (1, 0)
    >>> d.items()
    [(2, 0), (3, 0), (4, 0), (5, 0)]
    >>>

    字典项的迭代情况

    In [1]: d = dict([('one',1), ('two', 2), ('three', 3)])

    In [2]: d
    Out[2]: {'one': 1, 'three': 3, 'two': 2}

    In [3]: d.items()
    Out[3]: [('three', 3), ('two', 2), ('one', 1)]

    In [4]: d['two'] =4

    In [5]: d
    Out[5]: {'one': 1, 'three': 3, 'two': 4}

    In [6]: d.items()
    Out[6]: [('three', 3), ('two', 4), ('one', 1)]

    In [7]: del d['two']

    In [8]: d.items()
    Out[8]: [('three', 3), ('one', 1)]

    In [9]: d['two'] = 4

    In [10]: d.items()
    Out[10]: [('three', 3), ('two', 4), ('one', 1)]



  • 相关阅读:
    u-boot编译
    本地套接字
    内核线程
    长度为0数组
    Ubuntu安装KScope
    Python基础-运算符
    如何有效地记录 Java SQL 日志?
    解谜谷歌 DevOps:什么特质可以打造世界级可靠系统?
    如何打造前所未有的服务器端监控体验?
    趣味Python入门(一):初识Python
  • 原文地址:https://www.cnblogs.com/abeen/p/2205640.html
Copyright © 2011-2022 走看看