1. 程式人生 > >Python中collections模塊

Python中collections模塊

控制 命令 列表 忽略 bin stdin 淺拷貝 減少 統計

目錄

  • Python中collections模塊
    • Counter
    • defaultdict
    • OrderedDict
    • namedtuple
    • deque
    • ChainMap

Python中collections模塊

這個模塊實現了特定目標的容器,以提供Python標準內建容器 dict、list、set、tuple 的替代選擇。

  • Counter:字典的子類,提供了可哈希對象的計數功能
  • defaultdict:字典的子類,提供了一個工廠函數,為字典查詢提供了默認值
  • OrderedDict:字典的子類,保留了他們被添加的順序
  • namedtuple:創建命名元組子類的工廠函數
  • deque:類似列表容器,實現了在兩端快速添加(append)和彈出(pop)
  • ChainMap:類似字典的容器類,將多個映射集合到一個視圖裏面

Counter

Counter是一個dict子類,主要是用來對你訪問的對象的頻率進行計數。
常用方法:

  • elements():返回一個叠代器,每個元素重復計算的個數,如果一個元素的計數小於1,就會被忽略。
  • most_common([n]):返回一個列表,提供n個訪問頻率最高的元素和計數
  • subtract([iterable-or-mapping]):從叠代對象中減去元素,輸入輸出可以是0或者負數
  • update([iterable-or-mapping]):從叠代對象計數元素或者從另一個 映射對象 (或計數器) 添加。
# 統計字符出現的次數
>>> import collections
>>> collections.Counter('hello world')
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# 統計單詞數
>>> collections.Counter('hello world hello world hello nihao'.split())
Counter({'hello': 3, 'world': 2, 'nihao': 1})

常用的方法:

>>> c = collections.Counter('hello world hello world hello nihao'.split())
>>> c
Counter({'hello': 3, 'world': 2, 'nihao': 1})
# 獲取指定對象的訪問次數,也可以使用get()方法
>>> c['hello']
3
>>> c = collections.Counter('hello world hello world hello nihao'.split())
# 查看元素
>>> list(c.elements())
['hello', 'hello', 'hello', 'world', 'world', 'nihao']
# 追加對象,或者使用c.update(d)
>>> c = collections.Counter('hello world hello world hello nihao'.split())
>>> d = collections.Counter('hello world'.split())
>>> c
Counter({'hello': 3, 'world': 2, 'nihao': 1})
>>> d
Counter({'hello': 1, 'world': 1})
>>> c + d
Counter({'hello': 4, 'world': 3, 'nihao': 1})
# 減少對象,或者使用c.subtract(d)
>>> c - d
Counter({'hello': 2, 'world': 1, 'nihao': 1})
# 清除
>>> c.clear()
>>> c
Counter()

defaultdict

collections.defaultdict(default_factory)為字典的沒有的key提供一個默認的值。參數應該是一個函數,當沒有參數調用時返回默認值。如果沒有傳遞任何內容,則默認為None。

>>> d = collections.defaultdict()
>>> d
defaultdict(None, {})
>>> e = collections.defaultdict(str)
>>> e
defaultdict(<class 'str'>, {})

defaultdict的一個典型用法是使用其中一種內置類型(如str、int、list或dict)作為默認工廠,因為這些內置類型在沒有參數調用時返回空類型。

>>> d = collections.defaultdict(str)
>>> d
defaultdict(<class 'str'>, {})
>>> d['hello']
''
>>> d
defaultdict(<class 'str'>, {'hello': ''})
# 普通字典調用不存在的鍵時,將會拋異常
>>> e = {}
>>> e['hello']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'hello'

使用int作為default_factory的例子:

>>> from collections import defaultdict
>>> fruit = defaultdict(int)
>>> fruit['apple'] += 2 
>>> fruit
defaultdict(<class 'int'>, {'apple': 2})
>>> fruit
defaultdict(<class 'int'>, {'apple': 2})
>>> fruit['banana']  # 沒有對象時,返回0
0
>>> fruit
defaultdict(<class 'int'>, {'apple': 2, 'banana': 0})

使用list作為default_factory的例子:

>>> s = [('NC', 'Raleigh'), ('VA', 'Richmond'), ('WA', 'Seattle'), ('NC', 'Asheville')]
>>> d = collections.defaultdict(list)
>>> for k,v in s:
...      d[k].append(v)
... 
>>> d
defaultdict(<class 'list'>, {'NC': ['Raleigh', 'Asheville'], 'VA': ['Richmond'], 'WA': ['Seattle']})

OrderedDict

Python字典中的鍵的順序是任意的:它們不受添加的順序的控制。
collections.OrderedDict類提供了保留他們添加順序的字典對象。

>>> from collections import OrderedDict
>>> o = OrderedDict()
>>> o['key1'] = 'value1'
>>> o['key2'] = 'value2'
>>> o['key3'] = 'value3'
>>> o
OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

如果在已經存在的key上添加新的值,將會保留原來的key的位置,然後覆蓋value值。

>>> o['key1'] = 'value5'
>>> o
OrderedDict([('key1', 'value5'), ('key2', 'value2'), ('key3', 'value3')])

namedtuple

三種定義命名元組的方法:第一個參數是命名元組的構造器(如下的:Person,Human)

>>> from collections import namedtuple
>>> Person = namedtuple('Person', ['age', 'height', 'name'])
>>> Human = namedtuple('Human', 'age, height, name')
>>> Human2 = namedtuple('Human2', 'age height name')

實例化命令元組

>>> tom = Person(30,178,'Tom')
>>> jack = Human(20,179,'Jack')
>>> tom
Person(age=30, height=178, name='Tom')
>>> jack
Human(age=20, height=179, name='Jack')
>>> tom.age #直接通過  實例名+.+屬性 來調用
30
>>> jack.name
'Jack'

deque

collections.deque返回一個新的雙向隊列對象,從左到右初始化(用方法 append()) ,從 iterable (叠代對象) 數據創建。如果 iterable 沒有指定,新隊列為空。
collections.deque隊列支持線程安全,對於從兩端添加(append)或者彈出(pop),復雜度O(1)。
雖然list對象也支持類似操作,但是這裏優化了定長操作(pop(0)、insert(0,v))的開銷。
如果 maxlen 沒有指定或者是 None ,deques 可以增長到任意長度。否則,deque就限定到指定最大長度。一旦限定長度的deque滿了,當新項加入時,同樣數量的項就從另一端彈出。
支持的方法:

  • append(x):添加x到右端
  • appendleft(x):添加x到左端
  • clear():清楚所有元素,長度變為0
  • copy():創建一份淺拷貝
  • count(x):計算隊列中個數等於x的元素
  • extend(iterable):在隊列右側添加iterable中的元素
  • extendleft(iterable):在隊列左側添加iterable中的元素,註:在左側添加時,iterable參數的順序將會反過來添加
  • index(x[,start[,stop]]):返回第 x 個元素(從 start 開始計算,在 stop 之前)。返回第一個匹配,如果沒找到的話,升起 ValueError 。
  • insert(i,x):在位置 i 插入 x 。註:如果插入會導致一個限長deque超出長度 maxlen 的話,就升起一個 IndexError 。
  • pop():移除最右側的元素
  • popleft():移除最左側的元素
  • remove(value):移去找到的第一個 value。沒有拋出ValueError
  • reverse():將deque逆序排列。返回 None 。
  • maxlen:隊列的最大長度,沒有限定則為None。
>>> from collections import deque
>>> d = deque(maxlen=10)
>>> d
deque([], maxlen=10)
>>> d.extend('python')
>>> [i.upper() for i in d]
['P', 'Y', 'T', 'H', 'O', 'N']
>>> d.append('e')
>>> d.appendleft('f')
>>> d
deque(['f', 'p', 'y', 't', 'h', 'o', 'n', 'e'], maxlen=10)

ChainMap

一個 ChainMap 將多個字典或者其他映射組合在一起,創建一個單獨的可更新的視圖。 如果沒有 maps 被指定,就提供一個默認的空字典 。ChainMap是管理嵌套上下文和覆蓋的有用工具。

>>> from collections import ChainMap
>>> d1 = {'apple':1,'banana':2}
>>> d2 = {'orange':2,'apple':3,'pike':1}
>>> combined_d = ChainMap(d1,d2)
>>> reverse_combind_d = ChainMap(d2,d1)
>>> combined_d 
ChainMap({'apple': 1, 'banana': 2}, {'orange': 2, 'apple': 3, 'pike': 1})
>>> reverse_combind_d
ChainMap({'orange': 2, 'apple': 3, 'pike': 1}, {'apple': 1, 'banana': 2})
>>> for k,v in combined_d.items():
...      print(k,v)
... 
pike 1
apple 1
banana 2
orange 2
>>> for k,v in reverse_combind_d.items():
...      print(k,v)
... 
pike 1
apple 3
banana 2
orange 2

Python中collections模塊