collection 数据容器

    

        Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections

模块在这些内置数据类型的基础上,提供了几个额外的数据类型:


    namedtuple()。创建有名字域的元组子类的工厂函数。python 2.6新增。

    deque:双端队列,类似于列表,两端进栈和出栈都比较快速。python 2.4新增。

    Counter:字典的子类,用于统计哈希对象。python 2.7新增。

    OrderedDict:字典的子类,记录了添加顺序。python 2.7新增。

    defaultdict:dict的子类,调用一个工厂函数支持不存在的值。python 2.5新增。

    还提供了抽象基类,用来测试类是否提供了特殊接口,比如是哈希或者映射。



class {typename}(tuple):   # 可命名元祖
    '{typename}({arg_list})'

        namedtuple主要用来产生可以使用名称来访问元素的数据对象,通常用来增强代码的可

        读性, 在访问一些tuple类型的数据时尤其好用。

    

    

    def _make(cls, iterable, new=tuple.__new__, len=len):

             from collections import namedtuple

            websites = [
                        ('Sohu', 'http://www.google.com/', '张朝阳'),
                        ('Sina', 'http://www.sina.com.cn/', '王志东'),
                        ('163', 'http://www.163.com/', '丁磊')
                        ]
            Website = namedtuple('Website', ['name', 'url', 'founder'])
            for website in websites:
                website = Website._make(website)
                print(website)

               结果如下:

                Website(name='Sohu', url='http://www.google.com/', founder='张朝阳')

                Website(name='Sina', url='http://www.sina.com.cn/', founder='王志东')

                Website(name='163', url='http://www.163.com/', founder='丁磊')


    def _replace(_self, **kwds):
    def _asdict(self):

class Counter(dict):  # 计数器

     Counter() 的可用方法如下:


    def most_common(self, n=None): # 获取出现频率最高的几个元素


    def elements(self):   # 获取所有元素

      例:

        import collections

        c1=collections.Counter ('sdfsdgasdhgd')

        print c1

        print c1.most_common(3)

        for i in c1.elements():

                print i

        

        C:\Python27\python.exe "E:/python-file/learn - python.py"

        Counter({'d': 4, 's': 3, 'g': 2, 'a': 1, 'f': 1, 'h': 1})

        [('d', 4), ('s', 3), ('g', 2)]

        a

        d

        d

        d

        d

        g

        g

        f

        h

        s

        s

        s

        

        Process finished with exit code 0


    def update(*args, **kwds): # 有新添加的就添加到 collections.Counter()

            >>> c1

            Counter({'d': 4, 's': 3, 'g': 2, 'h': 1, 'f': 1, 'a': 1})

            >>> c2

            Counter({'a': 2, 'd': 1, 'c': 1, 'b': 1})

            >>> c1.update(c2)

            >>> c1

            Counter({'d': 5, 's': 3, 'a': 3, 'g': 2, 'h': 1, 'c': 1, 'b': 1, 'f': 1})


    def subtract(*args, **kwds):   # 相减 后 添加到  collections.Counter()

            >>> c1

            Counter({'d': 5, 's': 3, 'a': 3, 'g': 2, 'h': 1, 'c': 1, 'b': 1, 'f': 1})

            >>> c1.subtract(c2)

            >>> c1

            Counter({'d': 4, 's': 3, 'g': 2, 'h': 1, 'f': 1, 'a': 1, 'c': 0, 'b': 0})


    def copy(self):  # 浅层copy,只拷贝一层如有多层则一层之下默认指向深层地址

            


class OrderedDict(dict):  #  # 有序字典

                区别无序字典及有序字典的实例:

    

    import collections

    c1=collections.OrderedDict ()

    

    c1['k1']=1

    c1['k3']=1

    c1['k5']=1

    c1['k2']=1

    print c1

    c1={}

    c1['k1']=1

    c1['k3']=1

    c1['k5']=1

    c1['k2']=1

    print c1

    

    结果如下:

    OrderedDict([('k1', 1), ('k3', 1), ('k5', 1), ('k2', 1)])     ---有序字典

    {'k3': 1, 'k2': 1, 'k1': 1, 'k5': 1} ---无序字典

    

    自定义有序字典,字典变成有序的字典

    c1={}

    c1['k1']=1

    c1['k3']=3

    c1['k5']=5

    c1['k2']=2

    print c1

    li=['k1','k2','k3','k5']

    for i in li:

        print c1[i]                               

    

    C:\Python27\python.exe "E:/python-file/learn - python.py"

    {'k3': 3, 'k2': 2, 'k1': 1, 'k5': 5}

    1

    2

    3

    5

    

    Process finished with exit code 0


     有序字典方法,默认继承无序字典方法,如下:

    def clear(self): #  默认清除所有元素

            >>> c2

            OrderedDict([(0, 2), (1, 2), (2, 2)])

            >>> c2.clear()

            >>> c2

            OrderedDict()


    def copy(self): #  浅copy

            >>> c2 = c1.copy()

            >>> c2

            OrderedDict([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1))

 

    def fromkeys(cls, S, v=None): # (参见字典类)

            >>> c2=c1.fromkeys((i for i in range(3)),2)

            >>> c2

            OrderedDict([(0, 2), (1, 2), (2, 2)])


    def items(self, *args, **kwargs): #  有序字典同样具有字典的方法

            >>> c1

            OrderedDict([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1)])

            >>> c1.items()

            odict_items([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1)])


    def keys(self, *args, **kwargs): # 有序字典中所有元素的key值

            >>> c1

            OrderedDict([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1)])

            >>> c1.keys()

            odict_keys(['k4', 'k2', 'k3', 'k5'])


    def move_to_end(self, *args, **kwargs): # 将某一元素移到最后

            >>> c1

            OrderedDict([('k4', 1), ('k5', 1), ('k2', 1), ('k3', 1)])

            >>> c1.move_to_end('k5')

            >>> c1

            OrderedDict([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1)])


    def pop(self, k, d=None): #   删除某一元素,需要添加key值(见popitem)


    def popitem(self): #  删除元素,默认从最后删除无序添加key值

            >>> c1

            OrderedDict([('k4', 1), ('k5', 1), ('k2', 1), ('k3', 1), ('k1', 1)])

            >>> c1.popitem()

            ('k1', 1)

            >>> c1.pop()

            Traceback (most recent call last):

              File "", line 1, in

            TypeError: Required argument 'key' (pos 1) not found

            

    def setdefault(self, k, d=None): # 添加元素设置默认值,默认第二个参数为None

            >>> c1.setdefault(2,'v2')

            'v2'

            >>> c1

            OrderedDict([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1), (2, 'v2')])


    def update(self, *args, **kwargs): # 更新有序字典

            >>> c1

            OrderedDict([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1)])

            >>> c2

            OrderedDict([(0, 2), (1, 2), (2, 2)])

            >>> c1.update(c2)

            >>> c1

            OrderedDict([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1), (0, 2), 

                        (1, 2), (2, 2)])


    def values(self, *args, **kwargs): # 有序字典中所有元素的values值

            >>> c1

            OrderedDict([('k4', 1), ('k2', 1), ('k3', 1), ('k5', 1)])

            >>> c1.values()

            odict_values([1, 1, 1, 1])

     

class deque(object):  # 双向队列

   

    def append(self, *args, **kwargs): # 右侧添加

            >>> d2

            deque([ '>', '-', '-', '-', '<'])

            >>> d2.append('-')

            deque([ '>', '-', '-', '-', '<','-'])


    def appendleft(self, *args, **kwargs): # 左侧添加

             >>> d2

            deque([ '>', '-', '-', '-', '<'])

            >>> d2.appendleft('-')

            deque([ '-','>', '-', '-', '-', '<'])


    def clear(self, *args, **kwargs): # 清除所有元素


    def copy(self, *args, **kwargs): #   浅层copy

            >>> d2

            deque([ '>', '-', '-', '-', '<'])

            >>> d3=d2.copy()

            

    def count(self, value): # 

            >>> d2

            deque([ '>', '-', '-', '-', '<'])

            >>> d2.count('-')

            3

    

    def extend(self, *args, **kwargs): # 右侧扩展

            >>> d3

            deque(['1', '2', '3'])

            >>> d2

            deque([ '>', '-', '-', '-', '<'])

            >>> d2.extendleft(d3)

            >>> d2

            deque([ '>', '-', '-', '-','<','1', '2', '3'])


    def extendleft(self, *args, **kwargs): # 左侧扩展

            >>> d3

            deque(['1', '2', '3'])

            >>> d2

            deque([ '>', '-', '-', '-', '<'])

            >>> d2.extendleft(d3)

            >>> d2

            deque(['3','2', '1', '>', '-', '-', '-','<'])


   def index(self, value, start=None, stop=None): # 索引

            >>> d2

            deque(['3', ',', '2', ',', '1', '--', '>', '-', '-', '-', '-','<'])

            >>> d2.index('2')

            2


    def insert(self, index, p_object): # 可在指定位置插入

            >>> d3

            deque(['1', '2', '3'])

            >>> d3.insert(1,'4')

            >>> d3

            deque(['1', '4', '2', '3'])


    def pop(self, *args, **kwargs): #  右侧删除

            >>> d3

            deque(['1', '4', '2', '3'])

            >>> d3.pop()

            '3'

           

    def popleft(self, *args, **kwargs): # 左侧删除

            >>> d3.popleft()

            '1'

            >>> d3

            deque(['4', '2'])

 

    def remove(self, value): #  删除某一元素,需要加参数

            >>> d3.remove('4')

            >>> d3

            deque(['2'])


    def reverse(self): #  反转  

            >>> d3

            deque(['1', '2', '3'])

            >>> d3.reverse()

            >>> d3

            deque(['3', '2', '1'])


    def rotate(self, *args, **kwargs): #  下面这个是一个有趣的例子,主要使用了

                    deque的rotate方法来实现了一个无限循环的加载动画       

                  import sys

                        import  time

                        from collections import deque

                        de = deque('>------------<')

           while True:

                                print('\r %s ' % (''.join(de)))

                de.rotate(1)

                sys.stdout.flush()

                time.sleep(1)

          结果如下:

             >------------< 

             <>------------ 

             -<>----------- 

             --<>---------- 

             ---<>---------