在刷LeetCode時常看到討論區有使用Collections,研究一下發現原來Python除了List與Dict以外,還提供許多很好用的容器,能夠多加應用能讓程式更簡潔、效率更高,這篇就分享目前學到的幾個容器。
Counter 很好用的計數容器,能用大多dict的方法
from collections import Counter
c = Counter('gallahad')
#Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})c = Counter({'red': 4, 'blue': 2})
#Counter({'red': 4, 'blue': 2})c = Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]b = [1,1,1,3,3,2,1,3,4]
c = Counter(b)
#Counter({1: 4, 3: 3, 2: 1, 4: 1})
OrderedDict 有順序的dic
from collections import OrderedDictd = OrderedDict.fromkeys('abced')#abcedd.popitem(last=True)#abced.move_to_end('b')#aceb
DefaultDict 方便將Key:Value轉換成Key:List
from collections import defaultdicts = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)for k, v in s:
d[k].append(v)
#defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})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)#弄成set也很方便
deque 可以從左右append或pop
from collections import dequed = deque('abc')print(d)d.append('d')d.appendleft('i')print(d)d.pop()
d.popleft()list(reversed(d))d.extend('jkl')
d.extendleft('abc')
d.rotate(1)
參考資料:
https://docs.python.org/zh-tw/3/library/collections.html#collections.OrderedDict