Python のコレクションモジュールを探る

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

このチュートリアルでは、Pythonの組み込みのcollectionsモジュールを調べます。collectionsモジュールは、リスト、タプル、辞書などのPythonの組み込みのコンテナの機能を拡張するさまざまなコンテナデータ型を提供する強力なライブラリです。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/lists -.-> lab-7837{{"Python のコレクションモジュールを探る"}} python/tuples -.-> lab-7837{{"Python のコレクションモジュールを探る"}} python/dictionaries -.-> lab-7837{{"Python のコレクションモジュールを探る"}} python/function_definition -.-> lab-7837{{"Python のコレクションモジュールを探る"}} python/default_arguments -.-> lab-7837{{"Python のコレクションモジュールを探る"}} python/importing_modules -.-> lab-7837{{"Python のコレクションモジュールを探る"}} python/standard_libraries -.-> lab-7837{{"Python のコレクションモジュールを探る"}} python/data_collections -.-> lab-7837{{"Python のコレクションモジュールを探る"}} end

名前付きタプル

namedtupleはタプルのサブクラスで、読みやすさと自己文書化されたコードのために名前付きのフィールドを提供します。2次元空間上の点を表すために、named_tuple.pynamedtupleを作成しましょう。

## 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.pyCounterオブジェクトを作成しましょう。

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.pyOrderedDictを作成し、いくつかのキーと値のペアを追加しましょう。

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(int)

DefaultDictは、存在しないキーに対してデフォルト値を提供する辞書のサブクラスです。default_dict1.pyでデフォルト値が0DefaultDictを作成し、文内の単語の出現回数をカウントしましょう。

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)

Defaultdict(list)

次に、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)

Defaultdict(set)

最後に、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.pydequeを作成し、いくつかの操作を行いましょう。

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モジュールによって提供される主なクラスについて説明しました。これらには、namedtupleCounterOrderedDictDefaultDict、およびdequeが含まれます。これらのクラスは、さまざまなタスクに役立ち、Pythonツールキットに素晴らしい追加機能となります。