Python 學習之常用內建模塊(collections)

collections 是 Python 內建的一個集合模塊,提供了許多有用的集合類。

namedtuple

namedtuple 是一個函數,它用來創建一個自定義的 tuple 對象,並且規定了 tuple 元素的個數,並可以用屬性而不是索引來引用 tuple 的某個元素。
這樣一來,我們用namedtuple可以很方便地定義一種數據類型,它具備tuple的不變性,又可以根據屬性來引用,使用十分方便。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 內建模塊—collections '

__author__ = 'Kevin Gong'

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print('Point:', p.x, p.y)

deque

deque 是爲了高效實現插入和刪除操作的雙向列表,適合用於隊列和棧:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 內建模塊—collections '

__author__ = 'Kevin Gong'

from collections import deque

q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')
print(q)

defaultdict

使用 dict 時,如果引用的 Key 不存在,就會拋出 KeyError。如果希望 key 不存在時,返回一個默認值,就可以用 defaultdict:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 內建模塊—collections '

__author__ = 'Kevin Gong'

from collections import defaultdict

dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
print('dd[\'key1\'] =', dd['key1'])
print('dd[\'key2\'] =', dd['key2'])

Counter

Counter是一個簡單的計數器,例如,統計字符出現的個數:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 內建模塊—collections '

__author__ = 'Kevin Gong'

from collections import Counter

c = Counter()
for ch in 'hello kevin':
    c[ch] = c[ch] + 1
print(c)

結果:

Counter({'e': 2, 'l': 2, 'h': 1, 'o': 1, ' ': 1, 'k': 1, 'v': 1, 'i': 1, 'n': 1})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章