Skip to article frontmatterSkip to article content
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

# on charge la correction pour afficher des exemples
from skimlist import all_integers
incomings = [
    [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

from skimlist import keep_only_integers
incomings = [
    [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