整理自:博客 & Python中文
常用的有:defaultdict、deque、Ccounter
defaultdict
對象
class collections.
defaultdict
([default_factory[, ...]])
1)在有dict的情況下為何使用defaultdict:
使用dict
時,如果引用的Key不存在,就會拋出KeyError
。如果希望key不存在時,返回一個默認值,就可以用defaultdict
:
2) default_factory如何設置:
第一個參數 default_factory
提供了一個初始值。它默認為 None
。所有的其他參數都等同與 dict
構建器中的參數對待,包括關鍵詞參數。我的理解是若不設置default_factory,則當查找一個不存在的鍵時,就會報錯:
>>> d = defaultdict() # 沒有初始化參數default_factory >>> d defaultdict(None, {}) >>> d['a'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'a'
那么,default_factory可以取哪些可調用方法呢?有很多: list, set, int, lambda :None, lambda :0 等等。
- list
-
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) # 對於不存在的鍵,返回list() >>> for k, v in s: ... d[k].append(v) # d[k]就是列表 ... >>> sorted(d.items()) [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> d = defaultdict(list) >>> d defaultdict(<class 'list'>, {}) >>> d['a'] # 鍵‘a’不存在,則賦予空列表。相當於a=list() [] >>> d defaultdict(<class 'list'>, {'a': []}) # 注意到‘a’雖不存在,但也被添加到字典里
- set
-
>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] >>> d = defaultdict(set) # set() >>> for k, v in s: ... d[k].add(v) # d[k]就是集合 ... >>> sorted(d.items()) [('blue', {2, 4}), ('red', {1, 3})]
- int
>>> s = 'mississippi' >>> d = defaultdict(int) # int()總是為0 >>> for k in s: ... d[k] += 1 ... >>> sorted(d.items()) [('i', 4), ('m', 1), ('p', 2), ('s', 4)]
- lambda :None
-
>>> d = defaultdict(lambda : None) # f = lambda : None. f()總是返回None. 這個例子就沒有上面那么有實際意義 >>> d['a'] >>> d defaultdict(<function <lambda> at 0x0000025FF637F048>, {'a': None}) >>> d['a']+4 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
- lambda :0
-
>>> d = defaultdict(lambda : 0) # f = lambda : 0. f()總是返回None. 這個例子其實和int()一樣了 >>> d defaultdict(<function <lambda> at 0x0000025FF606A0D0>, {}) >>> d['a'] 0 >>> d['a']+=1 >>> d defaultdict(<function <lambda> at 0x0000025FF606A0D0>, {'a': 1})
deque
對象
class collections.
deque
([iterable[, maxlen]])
返回一個新的雙向隊列對象,從左到右初始化(用方法 append()
) ,從 iterable (迭代對象) 數據創建。如果 iterable 沒有指定,新隊列為空。
Deque隊列是由棧或者queue隊列生成的(發音是 “deck”,”double-ended queue”的簡稱)。Deque 支持線程安全,內存高效添加(append)和彈出(pop),從兩端都可以,兩個方向的大概開銷都是 O(1) 復雜度。
雖然 list
對象也支持類似操作,不過這里優化了定長操作和 pop(0)
和 insert(0, v)
的開銷。它們引起 O(n) 內存移動的操作,改變底層數據表達的大小和位置。
如果 maxlen 沒有指定或者是 None
,deques 可以增長到任意長度。否則,deque就限定到指定最大長度。一旦限定長度的deque滿了,當新項加入時,同樣數量的項就從另一端彈出。限定長度deque提供類似Unix filter tail
的功能。它們同樣可以用與追蹤最近的交換和其他數據池活動。
雙向隊列(deque)對象支持以下方法:
最常用的不過:append, appendleft, extend, extendleft, pop, popleft
>>> deq = deque(list(),5) >>> deq deque([], maxlen=5) >>> deq.append([1,2,3,4]) >>> deq.append(0) >>> deq.append(0) >>> deq.append(0) >>> deq.append(0) >>> deq deque([[1, 2, 3, 4], 0, 0, 0, 0], maxlen=5) # 因為設定了最大長度,所以再次添加6的時候,前端出隊列 >>> deq.append(6) >>> deq deque([0, 0, 0, 0, 6], maxlen=5)
雙向隊列(deque)對象支持以下方法:
-
append
(x) -
添加 x 到右端。
-
appendleft
(x) -
添加 x 到左端。
-
clear
() -
移除所有元素,使其長度為0.
-
copy
() -
創建一份淺拷貝。
3.5 新版功能.
-
count
(x) -
計算deque中個數等於 x 的元素。
3.2 新版功能.
-
extend
(iterable) -
擴展deque的右側,通過添加iterable參數中的元素。
-
extendleft
(iterable) -
擴展deque的左側,通過添加iterable參數中的元素。注意,左添加時,在結果中iterable參數中的順序將被反過來添加。
-
index
(x[, start[, stop]]) -
返回第 x 個元素(從 start 開始計算,在 stop 之前)。返回第一個匹配,如果沒找到的話,升起
ValueError
。3.5 新版功能.
-
insert
(i, x) -
在位置 i 插入 x 。
如果插入會導致一個限長deque超出長度 maxlen 的話,就升起一個
IndexError
。3.5 新版功能.
-
pop
() -
移去並且返回一個元素,deque最右側的那一個。如果沒有元素的話,就升起
IndexError
索引錯誤。
-
popleft
() -
移去並且返回一個元素,deque最左側的那一個。如果沒有元素的話,就升起
IndexError
索引錯誤。
-
remove
(value) -
移去找到的第一個 value。 如果沒有的話就升起
ValueError
。
-
reverse
() -
將deque逆序排列。返回
None
。
deque 其他用法
1. 過濾功能
def tail(filename, n=10): 'Return the last n lines of a file' with open(filename) as f: return deque(f, n)
>>> s=[1,2,3,4,5,6] >>> deque(s,3) deque([4, 5, 6], maxlen=3)
文檔里還有一些稍微復雜的例子。下面是python中棧和隊列的另一種表現:
棧直接用列表實現:
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append()
. To retrieve an item from the top of the stack, use pop()
without an explicit index. For example:
>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4]
隊列就是上面的deque:(列表插入或刪除都太低效了,所以用雙向隊列來實現)
It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
To implement a queue, use collections.deque
which was designed to have fast appends and pops from both ends. For example:
>>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])
Counter
對象
一個計數器工具提供快速和方便的計數。比如
>>> # Tally occurrences of words in a list
>>> cnt = Counter() >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1
>>> cnt Counter({'blue': 3, 'red': 2, 'green': 1})
class collections.
Counter
([iterable-or-mapping])
一個 Counter
是一個 dict
的子類,用於計數可哈希對象。它是一個集合,元素像字典鍵(key)一樣存儲,它們的計數存儲為值。計數可以是任何整數值,包括0和負數。 Counter
類有點像其他語言中的 bags或multisets。
元素從一個 iterable 被計數或從其他的 mapping (or counter)初始化:
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
Counter對象有一個字典接口,如果引用的鍵沒有任何記錄,就返回一個0,而不是彈出一個 KeyError
:
>>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero
0
設置一個計數為0不會從計數器中移去一個元素。使用 del
來刪除它:
>>> c['sausage'] = 0 # counter entry with a zero count
>>> del c['sausage'] # del actually removes the entry