Python爲咱們提供了4種基本的數據結構:list, tuple, dict, set,可是在處理數據量較大的情形的時候,這4種數據結構就明顯過於單一了,好比list做爲數組在某些情形插入的效率會比較低,有時候咱們也須要維護一個有序的dict。因此這個時候咱們就要用到Python標準庫爲咱們提供的collections包
了,它提供了多個有用的集合類,熟練掌握這些集合類,不只可讓咱們讓寫出的代碼更加Pythonic,也能夠提升咱們程序的運行效率。html
defaultdict(default_factory)
在普通的dict之上添加了default_factory,使得key不存在時會自動生成相應類型的value,default_factory參數能夠指定成list, set, int等各類合法類型。python
咱們如今有下面這樣一組list,雖然咱們有5組數據,可是仔細觀察後發現其實咱們只有3種color,可是每一種color對應多個值。如今咱們想要將這個list轉換成一個dict,這個dict的key對應一種color,dict的value設置爲一個list存放color對應的多個值。咱們可使用defaultdict(list)
來解決這個問題。git
>>> from collections import defaultdict >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) >>> for k, v in s: ... d[k].append(v) ... >>> sorted(d.items()) [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
以上等價於:github
>>> d = {} >>> for k, v in s: ... d.setdefault(k, []).append(v) ... >>> sorted(d.items()) [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
若是咱們不但願含有重複的元素,能夠考慮使用defaultdict(set)
。set相比list的不一樣之處在於set中不容許存在相同的元素。算法
>>> from collections import defaultdict >>> 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) ... >>> sorted(d.items()) [('blue', {2, 4}), ('red', {1, 3})]
Python3.6以前的dict是無序的,可是在某些情形咱們須要保持dict的有序性,這個時候可使用OrderedDict
,它是dict的一個subclass,可是在dict的基礎上保持了dict的有序型,下面咱們來看一下使用方法。數組
>>> # regular unsorted dictionary >>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} >>> # dictionary sorted by key >>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) >>> # dictionary sorted by value >>> OrderedDict(sorted(d.items(), key=lambda t: t[1])) OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) >>> # dictionary sorted by length of the key string >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0]))) OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
使用popitem(last=True)
方法可讓咱們按照LIFO(先進後出)的順序刪除dict中的key-value,即刪除最後一個插入的鍵值對,若是last=False就按照FIFO(先進先出)刪除dict中key-value。安全
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} >>> # dictionary sorted by key >>> d = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> d OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) >>> d.popitem() ('pear', 1) >>> d.popitem(last=False) ('apple', 4)
使用move_to_end(key, last=True)
來改變有序的OrderedDict對象的key-value順序,經過這個方法咱們能夠將排序好的OrderedDict對象中的任意一個key-value插入到字典的開頭或者結尾。數據結構
>>> d = OrderedDict.fromkeys('abcde') >>> d OrderedDict([('a', None), ('b', None), ('c', None), ('d', None), ('e', None)]) >>> d.move_to_end('b') >>> d OrderedDict([('a', None), ('c', None), ('d', None), ('e', None), ('b', None)]) >>> ''.join(d.keys()) 'acdeb' >>> d.move_to_end('b', last=False) >>> ''.join(d.keys()) 'bacde'
list存儲數據的優點在於按索引查找元素會很快,可是插入和刪除元素就很慢了,由於list是基於數組實現的。deque是爲了高效實現插入和刪除操做的雙向列表,適合用於隊列和棧,並且線程安全。app
list只提供了append和pop方法來從list的尾部插入/刪除元素,deque
新增了appendleft/popleft等方法容許咱們高效的在元素的開頭來插入/刪除元素。並且使用deque在隊列兩端append或pop元素的算法複雜度大約是O(1)
,可是對於list對象改變列表長度和數據位置的操做例如 pop(0)和insert(0, v)操做的複雜度高達O(n)
。性能
>>> from collections import deque >>> dq = deque(range(10), maxlen=10) >>> dq deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10) >>> dq.rotate(3) >>> dq deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6], maxlen=10) >>> dq.rotate(-4) >>> dq deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], maxlen=10) >>> dq.appendleft(-1) >>> dq deque([-1, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10) >>> dq.extend([11, 22, 33]) >>> dq deque([3, 4, 5, 6, 7, 8, 9, 11, 22, 33], maxlen=10) >>> dq.extendleft([10, 20, 30, 40]) >>> dq deque([40, 30, 20, 10, 3, 4, 5, 6, 7, 8], maxlen=10)
Count用來統計相關元素的出現次數。
>>> from collections import Counter >>> ct = Counter('abracadabra') >>> ct Counter({'a': 5, 'r': 2, 'b': 2, 'd': 1, 'c': 1}) >>> ct.update('aaaaazzz') >>> ct Counter({'a': 10, 'z': 3, 'r': 2, 'b': 2, 'd': 1, 'c': 1}) >>> ct.most_common(2) [('a', 10), ('z', 3)] >>> ct.elements() <itertools.chain object at 0x7fbaad4b44e0>
使用namedtuple(typename, field_names)
命名tuple中的元素來使程序更具可讀性。
>>> from collections import namedtuple >>> City = namedtuple('City', 'name country population coordinates') >>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) >>> tokyo City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667)) >>> tokyo.population 36.933 >>> tokyo.coordinates (35.689722, 139.691667) >>> tokyo[1] 'JP'
>>> City._fields ('name', 'country', 'population', 'coordinates') >>> LatLong = namedtuple('LatLong', 'lat long') >>> delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889)) >>> delhi = City._make(delhi_data) >>> delhi._asdict() OrderedDict([('name', 'Delhi NCR'), ('country', 'IN'), ('population', 21.935), ('coordinates', LatLong(lat=28.613889, long=77.208889))]) >>> for key, value in delhi._asdict().items(): print(key + ':', value) name: Delhi NCR country: IN population: 21.935 coordinates: LatLong(lat=28.613889, long=77.208889)
ChainMap
能夠用來合併多個字典。
>>> from collections import ChainMap >>> d = ChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' >>> d['snake'] = 'red' >>> d ChainMap({'lion': 'orange', 'zebra': 'black', 'snake': 'red'}, {'elephant': 'blue'}, {'lion': 'yellow'})
>>> del d['lion'] >>> del d['elephant'] Traceback (most recent call last): File "/usr/lib/python3.5/collections/__init__.py", line 929, in __delitem__ del self.maps[0][key] KeyError: 'elephant' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.5/collections/__init__.py", line 931, in __delitem__ raise KeyError('Key not found in the first mapping: {!r}'.format(key)) KeyError: "Key not found in the first mapping: 'elephant'"
從上面del['elephant']
的報錯信息能夠看出來,對於改變鍵值的操做ChainMap只會在第一個字典self.maps[0][key]
進行查找,新增長的鍵值對也都會加入第一個字典,咱們來改進一下ChainMap解決這個問題:
class DeepChainMap(ChainMap): 'Variant of ChainMap that allows direct updates to inner scopes' def __setitem__(self, key, value): for mapping in self.maps: if key in mapping: mapping[key] = value return self.maps[0][key] = value def __delitem__(self, key): for mapping in self.maps: if key in mapping: del mapping[key] return raise KeyError(key) >>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'}) >>> d['lion'] = 'orange' # update an existing key two levels down >>> d['snake'] = 'red' # new keys get added to the topmost dict >>> del d['elephant'] # remove an existing key one level down DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})
可使用new_child
來deepcopy一個ChainMap:
>>> from collections import ChainMap >>> a = {'a': 'A', 'c': 'C'} >>> b = {'b': 'B', 'c': 'D'} >>> m = ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) >>> m ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) >>> m['c'] 'C' >>> m.maps [{'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}] >>> a['c'] = 'E' >>> m['c'] 'E' >>> m ChainMap({'c': 'E', 'a': 'A'}, {'c': 'D', 'b': 'B'})
>>> m2 = m.new_child() >>> m2['c'] = 'f' >>> m2 ChainMap({'c': 'f'}, {'c': 'E', 'a': 'A'}, {'c': 'D', 'b': 'B'}) >>> m ChainMap({'c': 'E', 'a': 'A'}, {'c': 'D', 'b': 'B'}) >>> m2.parents ChainMap({'c': 'E', 'a': 'A'}, {'c': 'D', 'b': 'B'})
下面咱們來改進一下字典,查詢字典的時候將key轉換爲str的形式:
class StrKeyDict0(dict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] def get(self, key, default=None): try: return self[key] except KeyError: return default def __contains__(self, key): return key in self.keys() or str(key) in self.keys()
解釋一下上面這段程序:
infinite recursion
,self[str(key)]會再次調用__getitem__。k in my_dict
,由於str(key) in self
的形式,由於這會形成遞歸調用__contains__。這裏還強調一點,在Python2.x中dict.keys()會返回一個list,這意味着k in my_list必須遍歷list。在Python3.x中針對dict.keys()作了優化,性能更高,它會返回一個view如同set同樣,詳情參考官方文檔。
上面這個例子能夠用UserDict
改寫,而且將全部的key都以str的形式存儲,並且這種寫法更加經常使用簡潔:
import collections class StrKeyDict(collections.UserDict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] def __contains__(self, key): return str(key) in self.data def __setitem__(self, key, item): self.data[str(key)] = item
UserDict是MutableMapping和Mapping的子類,它繼承了MutableMapping.update和Mapping.get兩個重要的方法,因此上面咱們並無重寫get方法,能夠在源碼中看到它的實現和咱們上面的實現是差很少的。
DOCUMENTATION-COLLECTIONS
FLUENT-PYTHON
GitHub: https://github.com/ziwenxie
Blog: https://www.ziwenxie.site
本文爲做者原創,轉載請於開頭明顯處聲明博客出處:)