【Python】collectionsモジュールについて【標準ライブラリ】
目次
- collectionsモジュールとは?
- namedtuple: 名前付きタプル
- deque: 高速な両端キュー
- Counter: 要素の出現回数を数える
- defaultdict: デフォルト値を持つ辞書
- OrderedDict: 順序を保持する辞書
- ChainMap: 辞書の集合を扱う
collectionsモジュールとは?
Pythonの標準ライブラリである collections モジュールには、辞書やリストの拡張版のデータ構造が含まれています。
これにより、通常の dict や list では実装が難しい機能を簡単に扱うことができます。
namedtuple: 名前付きタプル
namedtuple は、タプルに名前を付け、通常のクラスのように属性アクセスを可能にするデータ構造です。
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age'])
p = Person(name="Alice", age=30)
print(p.name) # Alice
print(p.age) # 30
deque: 高速な両端キュー
deque(デック)は、リストよりも両端の追加・削除が高速なデータ構造です。
from collections import deque dq = deque([1, 2, 3]) dq.append(4) # 右端に追加 dq.appendleft(0) # 左端に追加 print(dq) # deque([0, 1, 2, 3, 4]) dq.pop() # 右端を削除 dq.popleft() # 左端を削除 print(dq) # deque([1, 2, 3])
Counter: 要素の出現回数を数える
Counter は、リストや文字列内の要素の出現回数をカウントするのに便利です。
from collections import Counter
words = ["apple", "banana", "apple", "orange", "banana", "banana"]
counter = Counter(words)
print(counter) # Counter({'banana': 3, 'apple': 2, 'orange': 1})
print(counter["banana"]) # 3
defaultdict: デフォルト値を持つ辞書
defaultdict は、辞書のキーが未登録でもエラーを発生させずにデフォルト値を返します。
from collections import defaultdict dd = defaultdict(int) # デフォルト値が0の辞書 dd["a"] += 1 print(dd["a"]) # 1 print(dd["b"]) # 0 (通常のdictならKeyError)
OrderedDict: 順序を保持する辞書
OrderedDict は、要素の追加順を記憶する辞書です(Python 3.7以降では通常の dict も順序を保持)。
from collections import OrderedDict
od = OrderedDict()
od["apple"] = 3
od["banana"] = 2
od["orange"] = 5
print(od) # OrderedDict([('apple', 3), ('banana', 2), ('orange', 5)])
ChainMap: 辞書の集合を扱う
ChainMap は、複数の辞書をまとめて管理できるデータ構造です。
from collections import ChainMap
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
chain = ChainMap(dict1, dict2)
print(chain["a"]) # 1
print(chain["b"]) # 2 (最初の辞書の値が優先)
print(chain["c"]) # 4