• fluent pythonchap31


    class collections.OrderedDict([items])

    返回一个 dict 子类的实例,它具有专门用于重新排列字典顺序的方法。

     

    """
    move_to_end(key, last=True)
    Move an existing key to either end of an ordered dictionary. 
    The item is moved to the right end if last is true (the default) 
    or to the beginning if last is false. 
    Raises KeyError if the key does not exist.
    """
    from collections import OrderedDict
    d = OrderedDict.fromkeys('abcde')
    print(d)
    #help(d.move_to_end)
    d.move_to_end('b')
    ''.join(d)
    
    d.move_to_end('b', last=True)
    ''.join(d)
    

      

    """
    popitem(last=True)
    有序字典的 popitem() 方法移除并返回一个 (key, value) 键值对。 
    如果 last 值为真,则按 LIFO 后进先出的顺序返回键值对,
    否则就按 FIFO 先进先出的顺序返回键值对。
    """
    from collections import OrderedDict
    d = OrderedDict.fromkeys('abcde')
    print(d.popitem(last=False))
    print(d) 

    但是普通的dict中,popitem()是没有参数的。

    在字典中,setdefault(key,[default])比get(k,[default])要快速。

    在dict中,k in my_dict.keys()中,这种操作在python3中非常快,因为dict.keys()返回的是一个视图。在python2中dict.keys()返回的是list,k in my_list这种操作效率很高,效率低很多。

    而实际测试下来,两种操作在python3中时间也基本一样,就是说你先取出来和后取出来,都一样,都是view。说到视图view,应该还记得SQL数据中的视图,其实就是一个虚拟的存在,可以认为是一个缓存一样,物理存储上是不存在的,所以读取速度特别快,数据库中一般如果经常操作一部分数据,也会把这部分数据做成view,使用完了再释放。

    d = {d:0 for d in range(10**7)}
    from time import perf_counter as pc
    t0=pc()
    n = 0
    for k in d.keys():
        n+=1
        
    t = pc()-t0
    print(t)
    
    lst = d.keys()
    n=0
    t1=pc()
    for k in lst:
        n+=1
        
    th = pc()-t1
    print(th) 
    

      

     PS.补充isinstance()函数和type()的使用和区别。 

    isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type().

    isinstance() 与 type() 区别:

    type() 不会认为子类是一种父类类型,不考虑继承关系。

    isinstance() 会认为子类是一种父类类型,考虑继承关系。

    如果要判断两个类型是否相同推荐使用 isinstance()。

  • 相关阅读:
    文档搜索引擎 vofill
    angularjs搭建项目步骤 vofill
    KlipperBox:帮助新手快速上手 Klipper 固件(上位机系统)
    在任意地方拿到SpringBoot管理的类(也称@Autowired拿到的值为空)
    SpringBoot获取客户端请求的IP
    vue.config.js中关于css.loaderOptions作用和配置
    git 协同开发常用命令
    scss 中的指令@import 、@media 、@extend、@mixin 、@include、 占位符%
    vue项目中容器布局自动撑满和盒子内容超出隐藏滚动条
    vue中vuecil3关于eslint告警0 errors and 7 warnings potentially fixable with the `fix` option.
  • 原文地址:https://www.cnblogs.com/jianyingzhou/p/15890564.html
Copyright © 2020-2023  润新知