python 内置模块:collections
生活随笔
收集整理的這篇文章主要介紹了
python 内置模块:collections
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
設置坐標:namedtuple
格式:
? ? ? ? 變量名 = namedtuple(任意名,list)
from?collections?import?namedtuplePoint?=?namedtuple('point',?['x',?'y',?'z']) p?=?Point(1,2,0) print(p.x) print(p.y,?p.z)print(isinstance(p,?tuple))運行結果:
1 2?0 True雙向隊列:deque
https://docs.python.org/2.7/library/collections.html?highlight=deque#collections.deque
from?collections?import?deque q?=?deque(['a',?'b',?'c']) q.append('x')???????#尾插 q.appendleft('y')???#頭插 print(q)運行結果:
deque(['y',?'a',?'b',?'c',?'x'])默認字典:defaultdict, 如果沒有該key值,默認輸出指定值。
from?collections?import?defaultdict dd?=?defaultdict(lambda:?'N/A') dd['key1']?=?'abc' print?(dd['key1'])?#?key1存在 print?(dd['key2'])運行結果:
abc N/A順序排列dist: OrderedDict
from?collections?import?OrderedDict d?=?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
from?collections?import?Counterc?=?Counter() for?ch?in?'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})轉載于:https://blog.51cto.com/13502993/2151744
總結
以上是生活随笔為你收集整理的python 内置模块:collections的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 错误记录
- 下一篇: 数据是互联网下半场产品人突围之道