日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 内置模块:collections

發布時間:2025/7/25 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。