any() と isinstance() を使用する
このステップでは、any() 関数と isinstance() 関数を組み合わせて、リストに特定の型の要素が少なくとも 1 つ含まれているかどうかをチェックする方法を学びます。これは、混合型リストを扱う際に特に有用です。
any() 関数は、イテラブル(リストなど)の要素のいずれかが真である場合に True を返し、それ以外の場合は False を返します。isinstance() 関数は、オブジェクトが指定されたクラスまたは型のインスタンスであるかどうかをチェックします。
これを実証する Python スクリプトを作成しましょう。VS Code エディタで、~/project ディレクトリに any_isinstance.py という名前の新しいファイルを作成します。
## Create a mixed-type list
my_list = [1, "hello", 3.14, True]
## Check if the list contains any integers
has_integer = any(isinstance(x, int) for x in my_list)
## Print the result
print("List contains an integer:", has_integer)
## Check if the list contains any strings
has_string = any(isinstance(x, str) for x in my_list)
## Print the result
print("List contains a string:", has_string)
## Check if the list contains any floats
has_float = any(isinstance(x, float) for x in my_list)
## Print the result
print("List contains a float:", has_float)
## Check if the list contains any booleans
has_bool = any(isinstance(x, bool) for x in my_list)
## Print the result
print("List contains a boolean:", has_bool)
ファイルを保存します。次に、ターミナルで python コマンドを使用してスクリプトを実行します。
python ~/project/any_isinstance.py
以下の出力が表示されるはずです。
List contains an integer: True
List contains a string: True
List contains a float: True
List contains a boolean: True
この例では、any() 関数の中にジェネレータ式 (isinstance(x, int) for x in my_list) を使用しています。このジェネレータ式は、要素 x が int のインスタンスである場合に True を生成し、それ以外の場合は False を生成します。そして、any() 関数はこれらの値のいずれかが True であるかどうかをチェックします。
出力がどのように変化するかを確認するために、リストを変更しましょう。my_list の最初の要素を浮動小数点数に変更します。
## Create a mixed-type list
my_list = [1.0, "hello", 3.14, True]
## Check if the list contains any integers
has_integer = any(isinstance(x, int) for x in my_list)
## Print the result
print("List contains an integer:", has_integer)
## Check if the list contains any strings
has_string = any(isinstance(x, str) for x in my_list)
## Print the result
print("List contains a string:", has_string)
## Check if the list contains any floats
has_float = any(isinstance(x, float) for x in my_list)
## Print the result
print("List contains a float:", has_float)
## Check if the list contains any booleans
has_bool = any(isinstance(x, bool) for x in my_list)
## Print the result
print("List contains a boolean:", has_bool)
ファイルを保存して再度実行します。
python ~/project/any_isinstance.py
今度は以下の出力が表示されるはずです。
List contains an integer: False
List contains a string: True
List contains a float: True
List contains a boolean: True
これで、リストに整数が含まれなくなったので、has_integer は False になります。
この手法は、リストの内容を検証したり、リストに含まれる要素の型に基づいて異なるアクションを実行したりする際に役立ちます。