Utiliser any()
avec isinstance()
Dans cette étape, vous apprendrez à utiliser la fonction any()
en combinaison avec la fonction isinstance()
pour vérifier si une liste contient au moins un élément d'un type spécifique. Cela est particulièrement utile lorsqu'on travaille avec des listes de types mixtes.
La fonction any()
renvoie True
si au moins un élément d'un itérable (comme une liste) est vrai. Sinon, elle renvoie False
. La fonction isinstance()
vérifie si un objet est une instance d'une classe ou d'un type spécifié.
Créons un script Python pour démontrer cela. Dans l'éditeur VS Code, créez un nouveau fichier nommé any_isinstance.py
dans le répertoire ~/project
.
## 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)
Enregistrez le fichier. Maintenant, exécutez le script en utilisant la commande python
dans le terminal :
python ~/project/any_isinstance.py
Vous devriez voir la sortie suivante :
List contains an integer: True
List contains a string: True
List contains a float: True
List contains a boolean: True
Dans cet exemple, nous avons utilisé une expression génératrice (isinstance(x, int) for x in my_list)
à l'intérieur de la fonction any()
. Cette expression génératrice renvoie True
si un élément x
est une instance de int
, et False
sinon. La fonction any()
vérifie ensuite si l'une de ces valeurs est True
.
Modifions la liste pour voir comment la sortie change. Changez le premier élément de my_list
en un nombre à virgule flottante :
## 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)
Enregistrez le fichier et exécutez-le à nouveau :
python ~/project/any_isinstance.py
La sortie devrait maintenant être :
List contains an integer: False
List contains a string: True
List contains a float: True
List contains a boolean: True
Maintenant, la liste ne contient plus d'entiers, donc has_integer
est False
.
Cette technique est utile pour valider le contenu d'une liste ou pour effectuer différentes actions en fonction des types d'éléments présents dans la liste.