Collections Class
This class is equivalent to an extension package that contains some extended operations for data types such as dictionaries, lists, tuples, and so on.
1. Counter counter
#计数器可以列出字符串和列表中元素出现的个数, and returned in a dictionary
>>> import collections>>> li=[' A ', ' B ', ' A ', ' C ', ' A ', ' B ', ' d ', ' d ', ' a ']>>> st= ' Asdasdasdasdasda ' >>> li_c=collections. Counter (LI) >>> st_c=collections. Counter (ST) >>> print li_ccounter ({' A ': 4, ' B ': 2, ' d ': 2, ' C ': 1}) >>> print st_ccounter ({' A ': 6, ' s ': 5, ' d ': 5}) #通过most_comm () method can specify the element that displays the top n bits of occurrences >>> print Li_c.most_common (3) [(' A ', 4), (' B ', 2), (' d ', 2)]
#update () method to add the statistical results of two counters
>>> import collections>>> li_a=[' A ', ' B ', ' A ', ' C ', ' a ']>>> li_b=[' B ', ' C ']>>> Li_a_ Co=collections. Counter (li_a) >>> li_b_co=collections. Counter (li_b) >>> print li_a_cocounter ({' A ': 3, ' C ': 1, ' B ': 1}) >>> print li_b_cocounter ({' C ': 1, ' B ': 1} ) >>> li_a_co.update (li_b_co) >>> print li_a_cocounter ({' A ': 3, ' C ': 2, ' B ': 2})
2. Ordered dictionary
#有序字典的的操作方法和标准字典完全一致, the only difference is that the key in an ordered dictionary can be shown sequentially, because an ordered dictionary is actually a list of keys that are stored on a standard dictionary and managed by a list of key
>>> Import collections>>> ord_dic=collections. Ordereddict () >>> ord_dic={}
3. Default Dictionary
#标准字典中value的值数据类型是需要提前定义的, otherwise it may be problematic to add data directly to value. For example, the following requirements:
There is a value set [11,22,33,44,55,66,77,88,99,90] that holds all values greater than 66 to the first key in the dictionary, and a value less than 66 to the value of the second key.
That is: {' K1 ': greater Than, ' K2 ': Less than 66}
#传统实现方式
li=[11,22,33,44,55,66,77,88,99,90]list_a=[]list_b=[]dic={' K1 ': list_a, ' K2 ': list_b}for i in li:if i > 66:dic[ ' K1 '].append (i) else:dic[' K2 '].append (i) Print dic
#用默认字典方式
Import collections#coding:utf-8li=[11, 33,44,55,66,77,88,99,90] #用默认字典方法提前定义value的数据类型dic = Collections.defaultdict (list) for value in Li:if value>66:dic[' K1 '].append (value) else:dic[' K2 ']. Append (value) print dic
Queue
#队列分为双向队列和单向队列, all queues are process-safe.
Two-way queue is the queue on both sides can be increased or decreased operation, is FIFO mode
One-way queues can increment and decrement operations only one side, so a one-way queue is a stack.
This article from "Thunderbolt Tofu" blog, declined reprint!
Python Training Day3 Essays