Counter: Processing a dictionary to calculate the number of occurrences of an element
#! /usr/bin/env python
#-*-Coding:utf-8-*-
# Author:wanghuafeng
Import Collections
#计数器, Counter
obj = collections. Counter ("Asdfghjgioccvbnjrtubvg6782bnsh2bn")
Print (obj)
#取前4个数, sort by from more to less
ret = Obj.most_common (4)
Print (ret)
#obj: Processed data
For k,v in Obj.items ():
Print (k, v)
#elements: Raw value, unprocessed
For I in Obj.elements ():
Print (i)
#! /usr/bin/env python
#-*-Coding:utf-8-*-
# Author:wanghuafeng
Import Collections
obj = collections. Counter ([' 11 ', ' 22 ', ' 33 ', ' 44 ', ' 55 '])
Print (obj)
#增加
Obj.update ([' Eric ', ' 11 ', ' 11 '])
Print (obj)
#删除
Obj.subtract ([' Eric ', ' 11 ', ' 11 '])
Print (obj)
Ordered dictionaries
#! /usr/bin/env Python
#-*-coding:utf-8-*-
# Author:wanghuafeng
Import Collections
#列表 + dictionary = ordered dictionary, Key takes the element in the list
DiC = collections. Ordereddict ()
dic[' k1 '] = ' v1 '
dic[' k2 '] = ' v2 '
dic[' k3 '] = ' v3 '
dic[' K4 '] = ' v4 '
dic[' K5 '] = ' v5 '
DiC [' K6 '] = ' V6 '
dic[' K7 '] = ' v7 '
dic[' k8 '] = ' V8 '
Print (DIC)
#! /usr/bin/env python
#-*-Coding:utf-8-*-
# Author:wanghuafeng
Import Collections
#列表 + dictionary = ordered dictionary, key takes the element from the list
DIC = collections. Ordereddict ()
dic[' k1 '] = ' v1 '
dic[' k2 '] = ' v2 '
dic[' K3 '] = ' v3 '
dic[' K4 '] = ' v4 '
dic[' K5 '] = ' v5 '
dic[' K6 '] = ' V6 '
dic[' K7 '] = ' v7 '
dic[' K8 '] = ' V8 '
Print (DIC)
#移动到最后
Dic.move_to_end (' K1 ')
Print (DIC)
#后进先出
Dic.popitem ()
Print (DIC)
#指定取数, Pop will take out the number of the appropriation
ret = Dic.pop (' K3 ')
Print (DIC)
Print (ret)
#设置默认值, if there is no action, increase if not present
Dic.setdefault (' K9 ', ' 22 ')
Print (DIC)
#更新
Dic.update ({' K1 ': ' v1 ', ' k10 ': ' V10 '})
Print (DIC)
Default Dictionary
#! /usr/bin/env python
#-*-Coding:utf-8-*-
# Author:wanghuafeng
Import Collections
values = [11, 22, 33, 44, 55, 66, 77, 88]
my_dict = collections.defaultdict (list)
For value in values:
If value > 33:
my_dict[' K1 '].append (value)
Else
my_dict[' K2 '].append (value)
Print (my_dict)
Can name a primitive ancestor
#创建类, Defaultdict
Mytupleclass = collections.namedtuple (' Mytupleclass ', [' X ', ' y ', ' z '])
Print (Help (Mytupleclass))
obj = Mytupleclass (11, 22, 33)
Print (obj.x)
Print (OBJ.Y)
Print (OBJ.Z)
Bidirectional queue
#! /usr/bin/env python
#-*-Coding:utf-8-*-
# Author:wanghuafeng
Import Collections
D = Collections.deque ()
#增加一个
D.append (' 1 ')
#往左增加
D.appendleft (' 10 ')
D.appendleft (' 1 ')
Print (d)
#统计个数
ret = D.count (' 1 ')
Print (ret)
#扩展, add to the right.
D.extend ([' yy ', ' qq ', ' 11 '])
Print (d)
#扩展, add to the left
D.extendleft ([' y1y ', ' q2q ', ' 131 '])
Print (d)
#从右取数插入左边
D.rotate (3)
Print (d)
One-way queues
Import queue
#创建单向队列
Q = queue. Queue ()
#增加数据
Q.put (' 123 ')
Q.put (' 456 ')
Print (Q.qsize ())
#按顺序取数据
Print (Q.get ())
Day 6 Collections Series