collections模塊經常使用的數據類型:app
(1)namedtuple(): #建立一個自定義的tuple對象,而且規定了tuple元素的個數,並能夠用屬性而不是索引來引用tuple的某個元素。 from collections import namedtuple p = namedtuple('p',['x','y','z']) p1 = p(2,3,5) print(p1.x,p1.y,p1.z) 輸出結果爲: 2 3 5
(2)deque(): #使用list存儲數據時,按索引訪問元素很快。因爲list是線性存儲,數據量大的時候,插入和刪除元素效率就很低。deque隊列是爲了高效的實現插入和刪除操做的雙向列表,適用於隊列和棧。 from collections import deque li1 = deque([1,2,3,4,5]) li1.append('a') li1.appendleft('m') print(li1) li1.pop() li1.popleft() print(li1) 輸出結果爲: deque(['m', 1, 2, 3, 4, 5, 'a']) deque([1, 2, 3, 4, 5])
(3)defaultdict(): #使用字典的時候,若是key值不存在就會報KeyError錯。若是想key不存在時,返回一個默認值,就能夠用defaultdict: from collections import defaultdict dd = defaultdict(lambda :'not exist!') dd['k1'] = '123' print(dd['k1']) print(dd['k2']) 輸出結果爲: 123 not exist!
(4)有序字典 from collections import OrderedDict dd = dict([('k1',1),('k2',2),('k3',3)]) print(dd) order_dd =OrderedDict([('k1',1),('k2',2),('k3',3)]) print(order_dd) 輸出結果爲: {'k3': 3, 'k2': 2, 'k1': 1} OrderedDict([('k1', 1), ('k2', 2), ('k3', 3)])
(5)Counter(): #計數器,統計字符串裏面全部元素出現次數。 from collections import Counter s = "A 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. " c = Counter(s) print(c.most_common(5)) #統計出現次數最多的5個元素 輸出結果爲: [(' ', 30), ('e', 18), ('s', 15), ('a', 13), ('t', 13)]