はじめに
このチュートリアルでは、Pythonの組み込みのcollections
モジュールを調べます。collections
モジュールは、リスト、タプル、辞書などのPythonの組み込みのコンテナの機能を拡張するさまざまなコンテナデータ型を提供する強力なライブラリです。
このチュートリアルでは、Pythonの組み込みのcollections
モジュールを調べます。collections
モジュールは、リスト、タプル、辞書などのPythonの組み込みのコンテナの機能を拡張するさまざまなコンテナデータ型を提供する強力なライブラリです。
namedtuple
はタプルのサブクラスで、読みやすさと自己文書化されたコードのために名前付きのフィールドを提供します。2次元空間上の点を表すために、named_tuple.py
にnamedtuple
を作成しましょう。
## Import collections
from collections import namedtuple
## Define a namedtuple type Point with x and y properties
Point = namedtuple('Point', ['x', 'y'])
## Create a Poinit object
p = Point(1, 2)
## Retrieve the properties of point
print(p.x)
print(p.y)
次に、端末でスクリプトを実行してください。
python named_tuple.py
出力:
1
2
Counter
は、コレクション内の要素の出現回数をカウントするdict
のサブクラスです。文字列内の文字の出現回数をカウントするために、counter.py
にCounter
オブジェクトを作成しましょう。
from collections import Counter
text = "hello, world!"
## コレクション内の要素の出現回数を取得し、辞書として返す
char_count = Counter(text)
print(char_count)
次に、端末でスクリプトを実行してください。
python counter.py
出力:
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ',': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})
OrderedDict
は、挿入された要素の順序を維持する辞書のサブクラスです。ordered_dict.py
にOrderedDict
を作成し、いくつかのキーと値のペアを追加しましょう。
from collections import OrderedDict
## Initialdefining OrderedDict
od = OrderedDict()
## Insert in key-value pairs
od['a'] = 1
od['b'] = 2
od['c'] = 3
## Iterate over the key-value pairs and print out the contents
for key, value in od.items():
print(key, value)
次に、端末でスクリプトを実行してください。
python ordered_dict.py
出力:
a 1
b 2
c 3
DefaultDict
は、存在しないキーに対してデフォルト値を提供する辞書のサブクラスです。default_dict1.py
でデフォルト値が0
のDefaultDict
を作成し、文内の単語の出現回数をカウントしましょう。
from collections import defaultdict
sentence = "the quick brown fox jumps over the lazy dog"
word_count1 = defaultdict(int)
for word in sentence.split():
## 単語の出現回数をカウント
word_count1[word] += 1
print(dict(word_count1))
次に、端末でスクリプトを実行してください。
python default_dict1.py
出力:
{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}
DefaultDict
を使用しなかった場合、対応するコードは次のようになります。
sentence = "the quick brown fox jumps over the lazy dog"
result = {}
for word in sentence.split():
if word in result:
result[word] += 1
else:
result[word] = 1
print(result)
次に、default_dict2.py
でデフォルト値が[]
のDefaultDict
を作成し、各文字に対する数値を格納しましょう。
from collections import defaultdict
data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
word_count2 = defaultdict(list)
for (key,value) in data:
## 各文字に対する数値を格納
word_count2[key].append(value)
print(dict(word_count2))
次に、端末でスクリプトを実行してください。
python default_dict2.py
出力:
{'a': [1, 1, 3], 'b': [1, 2, 3]}
DefaultDict
を使用しなかった場合、対応するコードは次のようになります。
data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
result = {}
for (key, value) in data:
if key in result:
result[key].append(value)
else:
result[key] = [value]
print(result)
最後に、default_dict3.py
でデフォルト値がset()
のDefaultDict
を作成し、各文字における重複しない数値を格納しましょう。
from collections import defaultdict
data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
word_count3 = defaultdict(set)
for (key,value) in data:
## 各文字における重複しない数値を格納
word_count3[key].add(value)
print(dict(word_count3))
次に、端末でスクリプトを実行してください。
python default_dict3.py
出力:
{'a': {1, 3}, 'b': {1, 2, 3}}
DefaultDict
を使用しなかった場合、対応するコードは次のようになります。
data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
result = {}
for (key, value) in data:
if key in result:
result[key].add(value)
else:
result[key] = {value}
print(result)
deque
(両端キュー)は、スタックとキューの一般化であり、両端からの高速なO(1)の追加と削除をサポートします。deque.py
にdeque
を作成し、いくつかの操作を行いましょう。
from collections import deque
d = deque([1, 2, 3, 4, 5])
## 右側に追加
d.append(6)
print("Append to the right:", d)
## 左側に追加
d.appendleft(0)
print("Append to the left:", d)
## 右側から削除
right_element = d.pop()
print("The right element:", right_element)
print("Pop from the right:", d)
## 左側から削除
left_element = d.popleft()
print("The left element:", left_element)
print("Pop from the left:", d)
## 両端キューを回転
d.rotate(2)
print("Rotate clockwise the deque:", d)
d.rotate(-2)
print("Rotate counterclockwise the deque:", d)
次に、端末でスクリプトを実行してください。
python deque.py
出力:
Append to the right: deque([1, 2, 3, 4, 5, 6])
Append to the left: deque([0, 1, 2, 3, 4, 5, 6])
The right element: 6
Pop from the right: deque([0, 1, 2, 3, 4, 5])
The left element: 0
Pop from the left: deque([1, 2, 3, 4, 5])
Rotate clockwise the deque: deque([4, 5, 1, 2, 3])
Rotate counterclockwise the deque: deque([1, 2, 3, 4, 5])
このチュートリアルでは、collections
モジュールによって提供される主なクラスについて説明しました。これらには、namedtuple
、Counter
、OrderedDict
、DefaultDict
、およびdeque
が含まれます。これらのクラスは、さまざまなタスクに役立ち、Pythonツールキットに素晴らしい追加機能となります。