python 内置模块:collections
设置坐标:namedtuple
格式:
变量名 = namedtuple(任意名,list)
fromcollectionsimportnamedtuplePoint=namedtuple('point',['x','y','z'])p=Point(1,2,0)print(p.x)print(p.y,p.z)print(isinstance(p,tuple))
运行结果:
120True
双向队列:deque
https://docs.python.org/2.7/library/collections.html?highlight=deque#collections.deque
fromcollectionsimportdequeq=deque(['a','b','c'])q.append('x')#尾插q.appendleft('y')#头插print(q)
运行结果:
deque(['y','a','b','c','x'])
默认字典:defaultdict, 如果没有该key值,默认输出指定值。
fromcollectionsimportdefaultdictdd=defaultdict(lambda:'N/A')dd['key1']='abc'print(dd['key1'])#key1存在print(dd['key2'])
运行结果:
abcN/A
顺序排列dist: OrderedDict
fromcollectionsimportOrderedDictd=dict([('a',1),('b',2),('c',3)])n={'a':1,'b':2,'c':3}print(d)#dict的Key是无序的print(n)#dict的Key是无序的od=OrderedDict([('a',1),('b',2),('c',3)])print(od)#OrderedDict的Key是有序的
运行结果:
{'c':3,'b':2,'a':1}{'c':3,'b':2,'a':1}OrderedDict([('a',1),('b',2),('c',3)])
计算数目:Counter
fromcollectionsimportCounterc=Counter()forchin'programming':c[ch]=c[ch]+1print(c)print(c)
运行结果:
Counter({'p':1})Counter({'r':1,'p':1})Counter({'r':1,'o':1,'p':1})Counter({'r':1,'o':1,'p':1,'g':1})Counter({'r':2,'o':1,'p':1,'g':1})Counter({'r':2,'o':1,'p':1,'g':1,'a':1})Counter({'r':2,'o':1,'p':1,'g':1,'a':1,'m':1})Counter({'r':2,'m':2,'o':1,'p':1,'g':1,'a':1})Counter({'r':2,'m':2,'o':1,'i':1,'p':1,'g':1,'a':1})Counter({'r':2,'m':2,'o':1,'i':1,'n':1,'p':1,'g':1,'a':1})Counter({'r':2,'g':2,'m':2,'o':1,'i':1,'n':1,'p':1,'a':1})Counter({'r':2,'g':2,'m':2,'o':1,'i':1,'n':1,'p':1,'a':1})
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。