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)]



  • 相关阅读:
    mac os apache 配置方法详细介绍
    反向代理-- WEB服务的加速器[转]
    Nginx 配置基于域名的虚拟
    centos yum 安装 mongodb 以及php扩展
    优秀 Java 程序员写代码的风格,不再留坑给别人
    优秀 Java 程序员写代码的风格
    Java 必看的 Spring 知识汇总!有比这更全的算我输!
    Java Web技术经验总结
    在Java中字符串是通过引用传递的?
    15个顶级Java多线程面试题及答案
  • 原文地址:https://www.cnblogs.com/abeen/p/2205640.html
Copyright © 2011-2022 走看看