collections是Python內建的一個集合模塊,提供了許多有用的集合類。html
python模塊分析之random(一)python
有序字典,至關於鍵值對列表;按照建立時的順序保持不變。spa
方法:繼承了dict結構,有其父類的全部的方法。日誌
import collections dt = {'a':1,'b':2,'c':3} o_dict = collections.OrderedDict(dt) # 通用方法 print(o_dict.keys()) # 返回字典全部的鍵順序列表 print(o_dict.items()) # 返回字典鍵值對元組組成的列表 print(o_dict.values()) # 返回字典全部的值組成的列表 print(o_dict.get('a')) # 返回以鍵查找的值,沒有返回None print(o_dict.pop('a')) # 以鍵彈出一個鍵值對 print(o_dict.clear()) # 清空字典,返回None print(o_dict.copy()) # 複製一個新的字典 print(o_dict.update({'a':2})) # 更新字典,沒有添加新的,有就更新 print(o_dict.setdefault('h', 9)) # 獲取一個鍵的值,若是沒有用默認值替代同時加入到字典,有直接返回值 print(o_dict.fromkeys(['a', 'f', 'g'], value=10)) # 建立一個值相同的字典,和原來的字典無關,類方法 # 特殊方法 print(o_dict.popitem(last=True)) # 以元組的方式從右端彈出鍵值對,last=False從左邊彈出 print(o_dict.move_to_end('a', last=True)) # 將一個鍵值對移到字典的末尾
import collections dt = {'a':1,'b':2,'c':3} # 可接受一個數據類型或無參數函數做爲初始化 o_dict = collections.defaultdict(list) o_dict1 = collections.defaultdict(lambda :10) print(o_dict) print(o_dict['a'].append(1)) # 默認全部的值都是列表 print(o_dict.get('a')) # 若是鍵存在,默認值爲10 print(o_dict1)
namedtuple是一個函數,它用來建立一個自定義的tuple對象,而且規定了tuple元素的個數,並能夠用屬性而不是索引來引用tuple的某個元素。code
import collections # 返回一個tuple類型,能夠經過自定義的屬性訪問而不是索引 User = collections.namedtuple('User', ['age','name']) user = User(19,'xiaoming') print(user.name) print(user.age)
import collections l = ['a', 'b', 'c'] dq = collections.deque(l) print(dq.append('c')) # 從右邊插入 print(dq.appendleft('c')) # 從左邊插入 print(dq.pop()) # 從右邊彈出 print(dq.popleft()) # 從左邊彈出 print(dq.rotate(3)) # 當參數爲正,從右邊數n個移到左邊;參數爲負數時,從左邊移動
import collections l = 'ffdsgdfgasfsghdgdaf' c = collections.Counter(l) # 直接生成以字符爲鍵,個數爲值的字典,值必須爲int print(c.most_common(3)) # 輸出排名前3的元組列表 print(list(c.elements())) # 輸出字符列表,從多到少 print(c.subtract('fsdfsfsf')) # 計算相減,獲得相減後的字典 print(c)
import collections dt1 = {'a':1, 'b':2} dt2 = {'c':1, 'd':2} c = collections.ChainMap([dt1, dt2]) # 建立一個映射視圖將多個字典合在一塊兒 # 特殊的方法 print(c.maps) # 返回全部的字典列表 # 在字典列表頭部插入字典,若是其參數爲空,則會默認插入一個空字典,而且返回一個改變後的ChainMap對象 print(c.new_child({'a':1}))