はじめに
この実験では、Python で集合が数値のみを含むかどうかをチェックする方法を学びます。この実験では、空集合、整数の集合、浮動小数点数の集合、整数と浮動小数点数の両方を含む混合集合など、数値集合の定義に焦点を当てています。また、集合が重複する値をどのように扱い、一意性を保証するかを調べます。
この実験では、numeric_sets.py という名前の Python ファイルを作成し、様々な集合を定義して出力するコードを追加し、スクリプトを実行して出力を観察する手順を案内します。set() コンストラクタの使い方や、集合が自動的に重複する値を削除する仕組みを学び、Python の集合の基本的な特性を理解します。
数値集合を定義する
このステップでは、Python で数値を含む集合を定義する方法を学びます。集合は、一意の要素からなる順序付けされていないコレクションです。つまり、集合には重複する値を含めることができません。ここでは、整数と浮動小数点数の集合を作成することに焦点を当てます。
まず、VS Code エディタを使用して、~/project ディレクトリに numeric_sets.py という名前の Python ファイルを作成しましょう。
## Create an empty set
empty_set = set()
print("Empty Set:", empty_set)
## Create a set of integers
integer_set = {1, 2, 3, 4, 5}
print("Integer Set:", integer_set)
## Create a set of floats
float_set = {1.0, 2.5, 3.7, 4.2, 5.9}
print("Float Set:", float_set)
## Create a mixed set (integers and floats)
mixed_set = {1, 2.0, 3, 4.5, 5}
print("Mixed Set:", mixed_set)
このファイルを ~/project ディレクトリに numeric_sets.py として保存します。次に、ターミナルで以下のコマンドを使用してスクリプトを実行します。
python numeric_sets.py
以下の出力が表示されるはずです。
Empty Set: set()
Integer Set: {1, 2, 3, 4, 5}
Float Set: {1.0, 2.5, 3.7, 4.2, 5.9}
Mixed Set: {1, 2.0, 3, 4.5, 5}
集合内の要素の順序は、定義した順序と同じであるとは限らないことに注意してください。これは、集合が順序付けされていないコレクションであるためです。また、集合は自動的に重複する値を削除します。
次に、集合の一意性を示すために、numeric_sets.py ファイルにいくつかの例を追加しましょう。
## Create a set with duplicate values
duplicate_set = {1, 2, 2, 3, 4, 4, 5}
print("Duplicate Set:", duplicate_set)
## Create a set from a list with duplicate values
duplicate_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(duplicate_list)
print("Unique Set from List:", unique_set)
変更を保存し、再度スクリプトを実行します。
python numeric_sets.py
以下の出力が表示されるはずです。
Empty Set: set()
Integer Set: {1, 2, 3, 4, 5}
Float Set: {1.0, 2.5, 3.7, 4.2, 5.9}
Mixed Set: {1, 2.0, 3, 4.5, 5}
Duplicate Set: {1, 2, 3, 4, 5}
Unique Set from List: {1, 2, 3, 4, 5}
ご覧の通り、duplicate_set と unique_set は、重複する値を使って作成しようとしたにもかかわらず、どちらも一意の値のみを含んでいます。
all() と isinstance() を使用する
このステップでは、all() 関数と isinstance() 関数を組み合わせて、集合内のすべての要素が特定の数値型であるかどうかをチェックする方法を学びます。これは、集合に対して操作を行う前にその内容を検証するのに役立ちます。
all() 関数は、イテラブル(集合など)内のすべての要素が真である場合に True を返します。isinstance() 関数は、オブジェクトが指定されたクラスまたは型のインスタンスであるかどうかをチェックします。
前のステップで作成した numeric_sets.py ファイルを変更して、これらのチェックを含めましょう。VS Code エディタで numeric_sets.py を開き、以下のコードを追加します。
def check_if_all_are_integers(input_set):
"""Checks if all elements in the set are integers."""
return all(isinstance(x, int) for x in input_set)
def check_if_all_are_floats(input_set):
"""Checks if all elements in the set are floats."""
return all(isinstance(x, float) for x in input_set)
## Example usage:
integer_set = {1, 2, 3, 4, 5}
float_set = {1.0, 2.5, 3.7, 4.2, 5.9}
mixed_set = {1, 2.0, 3, 4.5, 5}
print("Are all elements in integer_set integers?", check_if_all_are_integers(integer_set))
print("Are all elements in float_set floats?", check_if_all_are_floats(float_set))
print("Are all elements in mixed_set integers?", check_if_all_are_integers(mixed_set))
print("Are all elements in mixed_set floats?", check_if_all_are_floats(mixed_set))
ファイルを保存し、以下のコマンドを使用して実行します。
python numeric_sets.py
以下の出力が表示されるはずです。
Are all elements in integer_set integers? True
Are all elements in float_set floats? True
Are all elements in mixed_set integers? False
Are all elements in mixed_set floats? False
この出力から、integer_set は整数のみを含み、float_set は浮動小数点数のみを含み、mixed_set は整数と浮動小数点数の混合を含むことがわかります。したがって、整数と浮動小数点数のチェックではどちらも False が返されます。
次に、すべての要素が整数または浮動小数点数(つまり、数値)であるかどうかをチェックする関数を追加しましょう。
def check_if_all_are_numeric(input_set):
"""Checks if all elements in the set are either integers or floats."""
return all(isinstance(x, (int, float)) for x in input_set)
print("Are all elements in mixed_set numeric?", check_if_all_are_numeric(mixed_set))
string_set = {"a", "b", "c"}
print("Are all elements in string_set numeric?", check_if_all_are_numeric(string_set))
ファイルを保存し、再度実行します。
python numeric_sets.py
以下の出力が表示されるはずです。
Are all elements in integer_set integers? True
Are all elements in float_set floats? True
Are all elements in mixed_set integers? False
Are all elements in mixed_set floats? False
Are all elements in mixed_set numeric? True
Are all elements in string_set numeric? False
これにより、all() と isinstance() を使用して集合内の要素の型を検証する方法が示されています。
空集合を扱う
このステップでは、all() 関数と isinstance() 関数を使用する際に空の集合をどのように扱うかを学びます。空の集合は要素を含まないため、特殊なケースです。これらの関数が空の集合に対してどのように動作するかを理解することは、堅牢なコードを書くために重要です。
all() 関数を空の集合と一緒に使用した場合に何が起こるかを考えてみましょう。all() 関数は、イテラブル内のすべての要素が真である場合に True を返します。空の集合には要素がないため、「すべて」の要素が真であると主張することができます。なぜなら、偽である要素が存在しないからです。
これを実証するために、numeric_sets.py ファイルを変更しましょう。VS Code エディタで numeric_sets.py を開き、以下のコードを追加します。
def check_if_all_are_integers(input_set):
"""Checks if all elements in the set are integers."""
return all(isinstance(x, int) for x in input_set)
## Example with an empty set:
empty_set = set()
print("Is empty_set all integers?", check_if_all_are_integers(empty_set))
ファイルを保存し、以下のコマンドを使用して実行します。
python numeric_sets.py
以下の出力が表示されるはずです。
Is empty_set all integers? True
この結果は最初は直感的でないように思えるかもしれません。しかし、これは all() 関数の定義と一致しています。
次に、空の集合を明示的に異なる方法で扱いたいシナリオを考えてみましょう。all() を使用する前に、空の集合かどうかをチェックすることができます。
def check_if_all_are_integers_safe(input_set):
"""Checks if all elements in the set are integers, handling empty sets explicitly."""
if not input_set:
return False ## Or True, depending on your desired behavior for empty sets
return all(isinstance(x, int) for x in input_set)
empty_set = set()
print("Is empty_set all integers (safe)?", check_if_all_are_integers_safe(empty_set))
integer_set = {1, 2, 3}
print("Is integer_set all integers (safe)?", check_if_all_are_integers_safe(integer_set))
ファイルを保存し、再度実行します。
python numeric_sets.py
以下の出力が表示されるはずです。
Is empty_set all integers (safe)? False
Is integer_set all integers (safe)? True
この例では、check_if_all_are_integers_safe 関数は空の集合に対して False を返します。if not input_set: ブロックの戻り値を、あなたの特定のニーズに合わせて変更することができます。空の集合を明示的に扱うことで、コードに予期しない動作が発生するのを防ぐことができます。
まとめ
この実験では、Python で数値を含む集合(空の集合、整数の集合、浮動小数点数の集合、整数と浮動小数点数の両方を含む混合集合など)を定義する方法を学びました。また、集合は順序付けされていないコレクションであり、重複する値を自動的に削除することも確認しました。
この実験では、直接集合を作成する方法と、重複する値を含むリストから集合を作成する方法を示し、集合が一意の要素のみを保持する特性を強調しました。これらの例を通じて、集合がさまざまな数値型をどのように扱い、冗長性を排除するかを実践的に理解することができました。



