セットの特性を理解する
このステップでは、Python のセット (set) の特性について詳しく調べます。セットは単なる一意の要素のコレクションではありません。セットはさまざまな操作をサポートしており、データ操作において強力なツールとなります。要素の追加、削除、および和集合、積集合、差集合などの一般的なセット操作の実行方法を探ります。
まずはセットに要素を追加する方法を見てみましょう。
-
VS Code エディタを使って、~/project
ディレクトリ内の set_example.py
ファイルを開きます。
-
add()
メソッドを使ってセットに要素を追加するようにファイルを編集します。
## Create a set
my_set = {1, 2, 3}
## Add elements to the set
my_set.add(4)
my_set.add(5)
## Print the set
print(my_set)
-
ファイルを保存します。
-
ターミナルで python
コマンドを使ってスクリプトを実行します。
python set_example.py
以下のような出力が表示されるはずです。
{1, 2, 3, 4, 5}
次に、セットから要素を削除する方法を見てみましょう。
-
remove()
メソッドを使って要素を削除するように set_example.py
ファイルを編集します。
## Create a set
my_set = {1, 2, 3, 4, 5}
## Remove an element from the set
my_set.remove(3)
## Print the set
print(my_set)
-
ファイルを保存します。
-
再度スクリプトを実行します。
python set_example.py
以下のような出力が表示されるはずです。
{1, 2, 4, 5}
セットに存在しない要素を削除しようとすると、KeyError
が発生することに注意してください。これを避けるには、要素が存在しない場合にエラーを発生させない discard()
メソッドを使用できます。
```python
## Create a set
my_set = {1, 2, 3, 4, 5}
## Discard an element from the set
my_set.discard(6) ## No error raised
## Print the set
print(my_set)
```
最後に、いくつかの一般的なセット操作を探ってみましょう。
-
和集合、積集合、差集合の操作を実行するように set_example.py
ファイルを編集します。
## Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
## Union of the sets
union_set = set1.union(set2)
print("Union:", union_set)
## Intersection of the sets
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)
## Difference of the sets (elements in set1 but not in set2)
difference_set = set1.difference(set2)
print("Difference:", difference_set)
-
ファイルを保存します。
-
再度スクリプトを実行します。
python set_example.py
以下のような出力が表示されるはずです。
Union: {1, 2, 3, 4, 5, 6, 7}
Intersection: {3, 4, 5}
Difference: {1, 2}
これらのセットの特性と操作を理解することで、Python でさまざまなデータ操作タスクにセットを効果的に使用できるようになります。