Python でのセットの操作

PythonBeginner
オンラインで実践に進む

はじめに

この実験(Lab)では、Python における集合(sets)のハンズオン経験を積みます。集合は、一意で順序付けられていない要素を格納するために使用される基本的なデータ構造です。要素がコレクション内に存在するかどうかの確認や、数学的な集合演算の実行などにおいて非常に効率的です。

集合の作成方法、要素の追加と削除、および和集合(union)、積集合(intersection)、差集合(difference)などの一般的な操作の実行方法を学びます。最後に、リストから重複した項目を容易に削除するために集合を使用する、実践的な応用例を確認します。

セットの作成と要素の追加

この最初のステップでは、集合の作成方法と、既存の集合に新しい要素を追加する方法を学びます。集合は一意なアイテムの集まりであり、重複する要素は自動的に破棄されます。

お使いの環境には set_basics.py という名前の空のファイルが含まれています。エディタの左側にあるファイルエクスプローラーを使用して、~/project/set_basics.py を見つけて開いてください。

以下の Python コードをファイルに追加します。このコードは、集合を作成するいくつかの方法を示しています。

## Method 1: Using curly braces {}
## This creates a set with initial elements.
my_set = {'apple', 'banana', 'cherry'}
print("Set created with braces:", my_set)
print("Type of my_set:", type(my_set))

## Note: Sets automatically remove duplicate elements.
duplicate_set = {'apple', 'banana', 'apple'}
print("Set with duplicates:", duplicate_set)

## Method 2: Using the set() constructor on an iterable (like a string)
## This creates a set from the unique characters in the string.
char_set = set('hello world')
print("Set from a string:", char_set)

## Method 3: Creating an empty set
## You must use set() to create an empty set. {} creates an empty dictionary.
empty_set = set()
print("An empty set:", empty_set)
print("Type of empty_set:", type(empty_set))

ファイルを保存します。次に、エディタでターミナルを開き(メニュー: Terminal -> New Terminal を使用できます)、次のコマンドでスクリプトを実行します。

python ~/project/set_basics.py

以下のような出力が表示されます。集合内の要素の順序は保証されず、重複が削除されていることに注意してください。

Set created with braces: {'cherry', 'apple', 'banana'}
Type of my_set: <class 'set'>
Set with duplicates: {'banana', 'apple'}
Set from a string: {'d', 'l', 'o', 'r', 'w', ' ', 'h', 'e'}
An empty set: set()
Type of empty_set: <class 'set'>

次に、既存の集合に新しい要素を追加してみましょう。add() メソッドを使用して単一の要素を、update() メソッドを使用して複数の要素を追加できます。

以下のコードを set_basics.py ファイルの末尾に追加します。

## --- Adding elements ---
fruits = {'apple', 'banana'}
print("\nOriginal fruits set:", fruits)

## Use add() to add a single element
fruits.add('orange')
print("After adding 'orange':", fruits)

## add() has no effect if the element is already present
fruits.add('apple')
print("After adding 'apple' again:", fruits)

## Use update() to add multiple elements from an iterable (like a list)
fruits.update(['mango', 'grape'])
print("After updating with a list:", fruits)

ファイルを再度保存し、ターミナルから更新されたスクリプトを実行します。

python ~/project/set_basics.py

出力には、要素が追加された結果が含まれるようになります。

Set created with braces: {'cherry', 'apple', 'banana'}
Type of my_set: <class 'set'>
Set with duplicates: {'banana', 'apple'}
Set from a string: {'d', 'l', 'o', 'r', 'w', ' ', 'h', 'e'}
An empty set: set()
Type of empty_set: <class 'set'>

Original fruits set: {'banana', 'apple'}
After adding 'orange': {'banana', 'orange', 'apple'}
After adding 'apple' again: {'banana', 'orange', 'apple'}
After updating with a list: {'grape', 'mango', 'banana', 'orange', 'apple'}

これで、集合の作成方法と、新しい要素の追加による集合の変更方法を学びました。

セットからの要素の削除

このステップでは、集合から要素を削除するさまざまな方法を学びます。集合は順序付けられていないため、インデックスを使用してアイテムを削除することはできません。代わりに、Python はこの目的のために特定のメソッドを提供します。

~/project ディレクトリ内にある set_removal.py ファイルを見つけて開いてください。

以下のコードをファイルに追加します。これは、remove()discard()pop()、および clear() メソッドを示しています。

## --- Removing elements ---
my_set = {'a', 'b', 'c', 'd', 'e'}
print("Original set:", my_set)

## Method 1: remove()
## This removes a specified element. It raises a KeyError if the element is not found.
my_set.remove('b')
print("After removing 'b':", my_set)
## The following line would cause an error: my_set.remove('z')

## Method 2: discard()
## This also removes a specified element, but it does NOT raise an error if the element is not found.
print("\nStarting set for discard:", my_set)
my_set.discard('c')
print("After discarding 'c':", my_set)
my_set.discard('z') ## 'z' is not in the set, but no error occurs.
print("After discarding 'z' (non-existent):", my_set)

## Method 3: pop()
## This removes and returns an arbitrary element from the set.
## Since sets are unordered, you don't know which item will be popped.
print("\nStarting set for pop:", my_set)
popped_item = my_set.pop()
print("Popped item:", popped_item)
print("Set after pop():", my_set)

## Method 4: clear()
## This removes all elements from the set, leaving an empty set.
print("\nStarting set for clear:", my_set)
my_set.clear()
print("Set after clear():", my_set)

ファイルを保存します。次に、ターミナルからスクリプトを実行します。

python ~/project/set_removal.py

出力はこれと似ているはずです。集合は順序付けられていないため、pop() によって削除される要素はスクリプトを実行するたびに異なる可能性があります。

Original set: {'d', 'c', 'e', 'a', 'b'}
After removing 'b': {'d', 'c', 'e', 'a'}

Starting set for discard: {'d', 'c', 'e', 'a'}
After discarding 'c': {'d', 'e', 'a'}
After discarding 'z' (non-existent): {'d', 'e', 'a'}

Starting set for pop: {'d', 'e', 'a'}
Popped item: d
Set after pop(): {'e', 'a'}

Starting set for clear: {'e', 'a'}
Set after clear(): set()

これで、集合から要素を削除するための主要なメソッドと、remove()discard() の重要な違いを理解できました。

セット操作の実行

集合は、和集合(union)、積集合(intersection)、差集合(difference)などの数学的な演算を実行するのに特に強力です。このステップでは、Python でこれらの演算を実行する方法を学びます。

~/project ディレクトリ内にある set_operations.py ファイルを見つけて開いてください。

以下のコードをファイルに追加します。このコードは 2 つの集合を定義し、それらに対して 3 つの主要な集合演算を実行します。

set_a = {'a', 'b', 'c', 'd'}
set_b = {'c', 'd', 'e', 'f'}

print("Set A:", set_a)
print("Set B:", set_b)

## --- Union ---
## The union contains all unique elements from both sets.
## You can use the | operator or the .union() method.
union_set_op = set_a | set_b
union_set_method = set_a.union(set_b)
print("\nUnion with | operator:", union_set_op)
print("Union with .union() method:", union_set_method)

## --- Intersection ---
## The intersection contains only the elements that are common to both sets.
## You can use the & operator or the .intersection() method.
intersection_set_op = set_a & set_b
intersection_set_method = set_a.intersection(set_b)
print("\nIntersection with & operator:", intersection_set_op)
print("Intersection with .intersection() method:", intersection_set_method)

## --- Difference ---
## The difference contains elements that are in the first set but NOT in the second set.
## You can use the - operator or the .difference() method.
difference_set_op = set_a - set_b
difference_set_method = set_a.difference(set_b)
print("\nDifference (A - B) with - operator:", difference_set_op)
print("Difference (A - B) with .difference() method:", difference_set_method)

## Note that the order matters for difference
difference_b_a = set_b - set_a
print("Difference (B - A):", difference_b_a)

ファイルを保存し、ターミナルから実行します。

python ~/project/set_operations.py

出力には、各演算の結果が明確に表示されます。

Set A: {'d', 'c', 'a', 'b'}
Set B: {'d', 'c', 'f', 'e'}

Union with | operator: {'d', 'c', 'f', 'e', 'a', 'b'}
Union with .union() method: {'d', 'c', 'f', 'e', 'a', 'b'}

Intersection with & operator: {'d', 'c'}
Intersection with .intersection() method: {'d', 'c'}

Difference (A - B) with - operator: {'a', 'b'}
Difference (A - B) with .difference() method: {'a', 'b'}
Difference (B - A): {'f', 'e'}

演算子記号とメソッドの両方を使用して、集合に対して和集合、積集合、差集合の演算を正常に実行できました。

リストから重複を削除するためにセットを使用する

集合の最も一般的で実用的な用途の 1 つは、リストから重複する要素を迅速に削除することです。集合には一意の要素しか含めることができないため、リストを集合に変換し、それを再びリストに戻すことは、これを実現するためのシンプルかつ効率的な方法です。

この実験(Lab)の最終ファイルである remove_duplicates.py~/project ディレクトリ内で見つけて開いてください。

以下のコードをファイルに追加します。

## A list containing several duplicate numbers
numbers_list = [1, 5, 2, 3, 5, 1, 4, 2, 2, 5]
print("Original list with duplicates:", numbers_list)

## Step 1: Convert the list to a set.
## This automatically removes all duplicate elements.
unique_numbers_set = set(numbers_list)
print("Set created from list (duplicates gone):", unique_numbers_set)

## Step 2: Convert the set back to a list.
## The new list will only contain the unique elements.
unique_numbers_list = list(unique_numbers_set)
print("Final list with duplicates removed:", unique_numbers_list)

## Note: This process does not preserve the original order of the elements
## because sets are an unordered data structure.

ファイルを保存し、ターミナルから実行します。

python ~/project/remove_duplicates.py

出力は、元のリスト、中間的な集合、そして重複が削除された最終的なリストを示す、プロセス全体を実証します。

Original list with duplicates: [1, 5, 2, 3, 5, 1, 4, 2, 2, 5]
Set created from list (duplicates gone): {1, 2, 3, 4, 5}
Final list with duplicates removed: [1, 2, 3, 4, 5]

リストから重複を削除するという一般的なプログラミング上の問題を解決するために、集合に関する知識を適用することに成功しました。

まとめ

この実験(Lab)では、Python で集合を扱うための基本的なスキルを学びました。まず、異なる構文を使用して集合を作成し、集合が本質的に一意性を強制することを学習しました。次に、add()update() を使って要素を追加し、remove()discard()pop()clear() を使って要素を削除することで集合を変更する練習をし、これらのメソッド間の重要な違いに注目しました。

さらに、データ分析やアルゴリズム設計の基礎となる、和集合(|)、積集合(&)、差集合(-)といった主要な数学的集合演算を探求しました。最後に、この知識を実用的な用途に応用し、データクレンジングや準備における一般的なタスクである、リストから重複する項目を削除するためのエレガントなテクニックを実装しました。これで、Python プログラムで集合を効果的に使用する準備が整いました。