Python3入門(十三)——經常使用內置模塊之集合模塊collections

1.namedtuplehtml

  主要用來定義一種數據類型:它具備Tuple的不變性,並且又能經過屬性來訪問python

例如定義座標:spa

 

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1.x) #1
print(p2.y) #4

 

  注意此處,Point對象是tuple的一種子類,他只能有2個屬性code

2.dequehtm

  雙向鏈表,相比於List,插入刪除更快!對象

3.defaultdictblog

  使得dict在KeyError時有默認值字符串

4.OrderedDictget

  能夠實現有序的dict,是一個FIFO的dictit

5.ChainMap

  能夠把一組dict串成一個邏輯上的dict,自己也是一個dict

6.Counter

  一個計數器,自己也是dict,用來計算次數比較方便!(元素爲key,計數爲value)

  初始化方法:

c = Counter()  # 建立一個空的Counter類
c = Counter('gallahad')  # 從一個可iterable對象(list、tuple、dict、字符串等)建立
c = Counter({'a': 4, 'b': 2})  # 從一個字典對象建立
c = Counter(a=4, b=2)  # 從一組鍵值對建立

  使用示例:

>>> from collections import Counter
>>> c = Counter()
>>> for ch in 'programming':
...     c[ch] = c[ch] + 1
...
>>> c
Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'p': 1})
from collections import Counter

c = Counter("abcggss")
print(c)

結果:

Counter({'g': 2, 's': 2, 'a': 1, 'b': 1, 'c': 1})

經常使用操做,參考:http://www.pythoner.com/205.html

相關文章
相關標籤/搜索