collections模塊

1、collections

    collections模塊主要封裝了一些關於集合類的相關操做。好比,iterable,Iteratort等等,除此以外,collections還提供了一些除基本數據類型之外的數據集合類型。Counter,deque,OrderDict,defaultdict以及namedtupleapp

1. Counter

  • 計數器,主要用來計數
from collections import Counter

s = "Hello word"
print(Counter(s))  # Counter({'l': 2, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

lst = [11, 22, 33, 44, 55, 66, 55, 44, 44]
el = Counter(lst)

print(el[44])  # 3

 2. 雙向隊列

  • 既可從左邊添加數據,也可從右邊添加數據
  • 既可從左邊獲取數據,也可從右邊獲取數據
from collections import deque

q = deque()

q.append(11)
q.append(22)
q.appendleft(33)

print(q)              # deque([33, 11, 22])
print(q[0])           # 33

print(q.pop())        # 22
print(q.popleft())    # 33

3. namedtuple(命名元組)

  • 給元組內的元素進行命名
from collections import namedtuple

nt = namedtuple("Point", ["x", "y"])
p = nt(1, 2)

print(p.x)  # 1
print(p.y)  # 2

4. OrderedDict

  • 有序字典,按照存儲的順序保存

5. defaultdict

  • 給字典設置默認值。當key不存在時,直接獲取默認值
  • defaultdict括號內對象必須爲可調用對象
from collections import defaultdict

dic1 = defaultdict(list)
print(dic1["name"])       # []
print(dic1)               # defaultdict(<class 'list'>, {'name': []})


def func():
    return 'Tom'

dic = defaultdict(func)
print(dic["name"])        # Tom

 應用:spa

# 將lst = [11, 22, 33, 44, 55, 66, 77, 88, 99]大於等於66放入字典"key1"中,小於66放入字典"key2"中
from collections import defaultdict

lst = [11, 22, 33, 44, 55, 66, 77, 88, 99]
dic = defaultdict(list)
for el in lst:
    if el < 66:
        dic["key2"].append(el)
    else:
        dic["key1"].append(el)

dic = dict(dic)
print(dic)  # {'key2': [11, 22, 33, 44, 55], 'key1': [66, 77, 88, 99]}
相關文章
相關標籤/搜索