zoukankan      html  css  js  c++  java
  • python基础补漏-02-collection

    collection系列

         【1】计数器 Counter

    import collections
    res = collections.Counter("34234sdfgs45tsaf1")
    print res
    

    我们给这个对象穿了一个字符串对象 。

    他会统计 这个字符串对象 每个组成在字符串中出现的次数。

    --most_common 最少出现3次的

    ===========================================================================

     

    -- update 把一个Counter对象的内容 添加到另外一个Counter对象里

    ===========================================================================

     ---clear

    清楚数据

    ==========================================================================

    取值

    =========================================================

    --element

    ===============================================

      【2】有序字典

    我们都知道python的字典是无序的,那么怎么才能让他有序呢--Orderdict

    普通字典

     ====================================================

      【3】默认字典---带有默认值的字典

     我们都知道,在使用Python原生的数据结构dict的时候,如果用 d[key] 这样的方式访问, 当指定的key不存在时,是会抛出KeyError异常的。

    但是,如果使用defaultdict,只要你传入一个默认的工厂方法,那么请求一个不存在的key时, 便会调用这个工厂方法使用其结果来作为这个key的默认值。

    # -*- coding: utf-8 -*-
    from collections import defaultdict
    
    members = [
        # Age, name
        ['male', 'John'],
        ['male', 'Jack'],
        ['female', 'Lily'],
        ['male', 'Pony'],
        ['female', 'Lucy'],
    ]
    
    result = defaultdict(list)
    for sex, name in members:
        result[sex].append(name)
    
    print result
    
    # Result:
    defaultdict(<type 'list'>, {'male': ['John', 'Jack', 'Pony'], 'female': ['Lily', 'Lucy']})
    

      【4】双向队列 - deque从队列 头部快速增加和取出对象: .popleft().appendleft() 。

    # -*- coding: utf-8 -*-
    import sys
    import time
    from collections import deque
    
    fancy_loading = deque('>--------------------')
    
    while True:
        print '
    %s' % ''.join(fancy_loading),
        fancy_loading.rotate(1)
        sys.stdout.flush()
        time.sleep(0.08)

    你可能会说,原生的list也可以从头部添加和取出对象啊?就像这样:

    l.insert(0, v)
    l.pop(0)
    

    但是值得注意的是,list对象的这两种用法的时间复杂度是 O(n) ,也就是说随着元素数量的增加耗时呈 线性上升。而使用deque对象则是 O(1) 的复杂度,所以当你的代码有这样的需求的时候, 一定要记得使用deque。

    --关于这个 跟 python 内部如何处理数据结构有关

  • 相关阅读:
    Rate Control Mode
    帝国的困境:80-20法则
    ARM NEON 64bit 查找表替换
    Video Brightness Enhancement
    HDR(High Dynamic Range)
    C++ C++
    Machine Learning
    图像处理
    Facial landmark detection
    git
  • 原文地址:https://www.cnblogs.com/nerdlerss/p/6223121.html
Copyright © 2011-2022 走看看