程式扎記: [Python Std Library] Data Types : collections — High-performance container datatypes

標籤

2012年4月2日 星期一

[Python Std Library] Data Types : collections — High-performance container datatypes

翻譯自 這裡 
Preface : 
在這個模組支援了 container 需求並提供不同的實作, 讓你在已經支援的 dictlistset 與 tuple 外有其他選擇. 底下此模組提供的 container 種類 : 
 

Counter objects : 
此類別提供快速統計資料的處理, 先看範例如下 : 
>>> import re
>>> words = re.findall('\w+', open('doc.txt').read().lower())
>>> from collections import Counter
>>> Counter(words).most_common(10) # Find the ten most common words in doc.txt
[('the', 18), ('is', 9), ('to', 6), ('list', 6), ('of', 6), ('and', 6), ('are', 5), ('counts', 5), ('for', 4), ('length', 4)]

可以透過下面建構子建立物件 : 
- class collections.Counter([iterable-or-mapping]) 
Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

Count 提供 dict 的介面, 比較要注意的是如果你嘗試 access 一個不存在的鍵值, 0 會被返回而不是丟出 KeyError : 
>>> from collections import Counter
>>> c = Counter(['eggs', 'ham'])
>>> c['eggs']
1
>>> c['bacon']
0

接著我們來看看物件上有什麼函數可以用 : 
elements() 
Return an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order. If an element’s count is less than one, it will be ignored.
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

most_common([n]) 
Return a list of the n most common elements and their counts from the most common to the least. If n is not specified, this method returns all elements in the counter. Elements with equal counts are ordered arbitrarily :
>>> Counter('abracadabrafg').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

subtract([iterable-or-mapping]) 
Elements are subtracted from an iterable or from another mapping (or counter). Like dict.update() but subtracts counts instead of replacing them. Both inputs and outputs may be zero or negative.
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

update([iterable-or-mapping]) 
Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterableis expected to be a sequence of elements, not a sequence of (key, value) pairs.

底下是常見操作整理 : 
sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n:-1] # n least common elements
c += Counter() # remove zero and negative counts

更方便與直覺的, 某些數學運算子支援如下 : 
>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d # add two counters together: c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d # intersection: min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d # union: max(c[x], d[x])
Counter({'a': 3, 'b': 2})

deque objects : 
首先來看它的建構子 : 
class collections.deque([iterable[, maxlen]]) 
Returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.

Deque 物件支援下面方法 : 
append(x) 
Add x to the right side of the deque.

appendleft(x) 
Add x to the left side of the deque.

clear() 
Remove all elements from the deque leaving it with length 0.

count(x) 
New in version 2.7.
Count the number of deque elements equal to x.

extend(iterable) 
Extend the right side of the deque by appending elements from the iterable argument.

extendleft(iterable) 
Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.

pop() 
Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.

popleft() 
Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.

remove(value) 
New in version 2.5.
Removed the first occurrence of value. If not found, raises a ValueError.

reverse() 
New in version 2.7.
Reverse the elements of the deque in-place and then return None.

rotate(n) 
Rotate the deque n steps to the right. If n is negative, rotate to the left. Rotating one step to the right is equivalent to: d.appendleft(d.pop()).

在使用 deque 必須知道在 access 兩端的 element 所需的時間為 O(1) ; 但是在 random access 中間的 element 所需時間為 O(n). 因此如果你需要常常 random 存取中間的元素建議使用 list來實作. 底下為其使用範例 : 
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print elem.upper()
G
H
I

>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
>>> list(d) # list the contents of the deque
['g', 'h', 'i']
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'

>>> list(reversed(d)) # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d # search the deque
True
>>> d.extend('jkl') # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1) # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1) # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d)) # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear() # empty the deque
>>> d.pop() # cannot pop from an empty deque
Traceback (most recent call last):
File "", line 1, in -toplevel-
d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc') # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])

更多的 deque 應用可以參考 deque Recipes 

defaultdict objects : 
此類別的建構子如下 : 
class collections.defaultdict([default_factory[, ...]]) 
Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

因為此類別提供與 dict 相同的運算與函式, 接著我們直接來看範例 : 
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

如果你將 default_factory 設為 int 方便進行 counting 的計算 : 
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1 # 當鍵值第一次出現時, 初始值為 int() = 0
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

如果將 default_factory 設為 set : 
>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
... d[k].add(v)
...
>>> d.items()
[('blue', set([2, 4])), ('red', set([1, 3]))] # duplicate ('red', 1) will be drop

namedtuple() Factory Function for Tuples with Named Fields : 
此類別提供比 tuple 更強的功能與方便的操作, 建構子如下 : 
collections.namedtuple(typenamefield_names[, verbose=False][, rename=False]) 
Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

The field_names are a sequence of strings such as ['x', 'y']. Alternatively, field_names can be a single string with each fieldname separated by whitespace and/or commas, for example 'x y' or 'x, y'.

Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as classforreturnglobalpassprint, or raise.

If rename is true, invalid fieldnames are automatically replaced with positional names. For example, ['abc', 'def', 'ghi', 'abc'] is converted to ['abc', '_1', 'ghi', '_3'], eliminating the keyword def and the duplicate fieldname abc.

If verbose is true, the class definition is printed just before being built.

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

接著來看範例如何使用 : 
>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
...(略)...
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)

除了原本 tuple 舊有的函數與屬性, named tuple 支援以下新增的函數與屬性, 為了避免名稱上的 conflict, 名稱前會加上 underscore : 
- classmethod somenamedtuple._make(iterable) 
Class method that makes a new instance from an existing sequence or iterable.
>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)

somenamedtuple._asdict() 
Return a new OrderedDict which maps field names to their corresponding values :
>>> p._asdict()
OrderedDict([('x', 11), ('y', 22)])

somenamedtuple._replace(kwargs) 
Return a new instance of the named tuple replacing specified fields with new values :
>>> p = Point(x=11, y=22)
>>> p._replace(x=33) # 返回新物件
Point(x=33, y=22)
>>> p
Point(x=11, y=22)

somenamedtuple._fields 
Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples :
>>> p._fields
('x', 'y')
>>> Color = namedtuple('Color', 'red green blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)

如果你要從 named tuple 的某個 field 取出值的話, 可以使用 Built-in 函數 getattr() : 
>>> getattr(p, 'x') # p 為 named tuple ; 'x' 為 field 的名稱.
11

如果你要從 dictionray 轉成 named tuple, 可以使用 double-star-operator : 
>>> d = {'x': 11, 'y': 22}
>>> Point(**d)
Point(x=11, y=22)

既然 named tuple 也是類別, 所以你也可以繼承並新增客製函數 : 
 

OrderedDict objects : 
OrderedDict 類別與一般你使用到的 dict 內建類別沒有多大差異, 唯一不同是此類別會記住你 inserted key 的順序, 所以之後你取出時便可以按照插入的順序取出. 首先來看看建構子 : 
class collections.OrderedDict([items]) 
New in version 2.7.
Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

接著來看物件上的方法 : 
OrderedDict.popitem(last=True) 
This method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.

接著來看使用上的範例, 首先是透過 sorted() 與指定 key 的方式讓你決定 ordered dictionary 的順序 : 
 

Supplement : 
Collections Abstract Base Classes

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!