Licence CC BY-NC-ND Thierry Parmentelat & Arnaud Legout
filtrer une liste¶
filtrage par copie¶
Il s’agit d’écrire une fonction all_integers qui
accepte en entrée un itérable
retourne la liste de tous les entiers trouvés dans l’itérable (on ignore le reste)
bien sûr on les conserve dans l’ordre où on les trouve
# on charge la correction pour afficher des exemples
from skimlist import all_integersincomings = [
[1, 2, 3, 4, 'spam', 5, [4, 5]],
[(1, 2), 3, 4, 'spam', 5, 3.],
]# remarquez bien que les objets 'incoming' ne sont pas modifiés
for incoming in incomings:
print(10*'=')
print(f"incoming(avant) = {incoming}")
print(f"integers trouvés = {all_integers(incoming)}")
print(f"incoming(après) = {incoming} doit être intact")==========
incoming(avant) = [1, 2, 3, 4, 'spam', 5, [4, 5]]
integers trouvés = [1, 2, 3, 4, 5]
incoming(après) = [1, 2, 3, 4, 'spam', 5, [4, 5]] doit être intact
==========
incoming(avant) = [(1, 2), 3, 4, 'spam', 5, 3.0]
integers trouvés = [3, 4, 5]
incoming(après) = [(1, 2), 3, 4, 'spam', 5, 3.0] doit être intact
filtrage par effet de bord¶
Cette fois on veut une fonction keep_only_integers qui
accepte en entrée une liste
modifie cet objet en entrée pour ne garder que les éléments de type
int
from skimlist import keep_only_integersincomings = [
[1, 2, 3, 4, 'spam', 5, 'beans'],
[(1, 2), 3, 4, 'spam', 5, 'beans'],
]for incoming in incomings:
print(10*'=')
print(f"incoming(avant) = {incoming}")
print(f"all_integers = {all_integers(incoming)}")
print(f"incoming(après - intact) = {incoming}")
keep_only_integers(incoming)
print(f"incoming(modifié par keep_only_integers) = {incoming}")==========
incoming(avant) = [1, 2, 3, 4, 'spam', 5, 'beans']
all_integers = [1, 2, 3, 4, 5]
incoming(après - intact) = [1, 2, 3, 4, 'spam', 5, 'beans']
incoming(modifié par keep_only_integers) = [1, 2, 3, 4, 5]
==========
incoming(avant) = [(1, 2), 3, 4, 'spam', 5, 'beans']
all_integers = [3, 4, 5]
incoming(après - intact) = [(1, 2), 3, 4, 'spam', 5, 'beans']
incoming(modifié par keep_only_integers) = [3, 4, 5]
solution¶
ouvrez-moi
skimlist.py
def all_integers(iterable):
"""
retourne la liste des éléments entiers de iterable
iterable n'est pas modifié
"""
# la compréhension fabrique une nouvelle liste
return [x for x in iterable if isinstance(x, int)]
def keep_only_integers(liste):
"""
cette fois on suppose que l'entrée est une liste
et on **modifie** la liste pour ne garder que les entiers
"""
# attention à ne pas modifier le sujet du for dans le for
for x in liste[:]:
if not isinstance(x, int):
liste.remove(x)
# on ne retourne rien pour bien montrer à l'appelant
# qu'on a fait un effet de bord