Bien boucler en Python
En résumé :
dict.items(), dict.values()
sorted, enumerate, zip
all, any
min, max
sum
map
Lecture : Loop like a native
D’autres outils encore dans le module standard itertools
.
Comment boucler sur un dict ?
[1]:
mon_dict = {'un': 1, 'deux': 2, 'trois': 3, 'quatre': 4}
[2]:
# parcourir les clefs
for clef in mon_dict:
print('clef :', clef)
clef : un
clef : deux
clef : trois
clef : quatre
[3]:
# parcourir les valeurs
for valeur in mon_dict.values():
print('valeur :', valeur)
valeur : 1
valeur : 2
valeur : 3
valeur : 4
[4]:
# parcourir les pairs clef-valeur
for clef, valeur in mon_dict.items():
print(f'clef : {clef:>10} | valeur : {valeur:>10}')
clef : un | valeur : 1
clef : deux | valeur : 2
clef : trois | valeur : 3
clef : quatre | valeur : 4
Changer la manière d’itérer
[5]:
# sorted
l = [4., 6., 2., 4., 9., 1.]
for i in sorted(l):
print(i, end=' ')
1.0 2.0 4.0 4.0 6.0 9.0
[6]:
# enumerate
for indice, valeur in enumerate(l):
print(f'l[{indice:d}] = {valeur:.2f}')
l[0] = 4.00
l[1] = 6.00
l[2] = 2.00
l[3] = 4.00
l[4] = 9.00
l[5] = 1.00
[7]:
# zip
def f(a, b):
return f'a = {a:>8} | b = {b:>8}'
list_a = ['un', 'deux', 'trois', 'quatre']
list_b = [1, 2, 3, 4]
# comment appliquer f sur list_a-list_b ?
for (a, b) in zip(list_a, list_b):
print(f(a, b))
a = un | b = 1
a = deux | b = 2
a = trois | b = 3
a = quatre | b = 4
[8]:
list(zip(list_a, list_b))
[8]:
[('un', 1), ('deux', 2), ('trois', 3), ('quatre', 4)]
Parfois, il n’y a même pas besoin de faire sa boucle
all / any
[9]:
# on pourrait avoir besoin de ceci
def tous_vrai(iterable):
for element in iterable:
if not element:
return False
return True
# mais cela existe déjà
help(all)
Help on built-in function all in module builtins:
all(iterable, /)
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
[10]:
# on pourrait avoir besoin de ceci
def au_moins_un_vrai(iterable):
for element in iterable:
if element:
return True
return False
# mais cela existe déjà
help(any)
Help on built-in function any in module builtins:
any(iterable, /)
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
max / min
[11]:
# on pourrait avoir besoin de ceci
def max_sequence(iterable):
copie = list(iterable)
result = copie[0]
for valeur in copie[1:]:
result = max(result, valeur)
return resulr
# mais cela existe déjà
help(max)
Help on built-in function max in module builtins:
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
sum
[12]:
# on pourrait avoir besoin de ceci
def somme_sequence(iterable, start=0):
result = start
for valeur in iterable:
result += valeur
return result
# mais cela existe déjà
help(sum)
Help on built-in function sum in module builtins:
sum(iterable, /, start=0)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
map
[13]:
# on pourrait avoir besoin de ceci
def applique_sur_sequence(fontions, iterable):
result = []
for valeur in iterable:
result.append(fonction(valeur))
return result
# mais cela existe déjà
help(map)
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
Exercices
Creer un dict à partir d’une liste de clefs et d’une liste de valeurs.
Etant donné un dict dont les valeurs sont des entiers, extraire le sous-dict composé uniquement des valeurs paires.