Itérateurs et générateurs

by Christian Nguyen, Joseph Razik, last modified on 2019-10-18
iterateurs_generateurs

Itérateur

In [1]:
it = iter(range(10))
print(it)
print(next(it), next(it))
for it in range(10):
    print(it, '', end='')
print()
for it in [1, '2', 3]:  # une liste est un itérable
    print(it, '', end='')
print()
ll = list("python")  # usage implicite : chaîne itérable
print(ll[1])
<range_iterator object at 0x7f17adabf300>
0 1
0 1 2 3 4 5 6 7 8 9 
1 2 3 
y

Comprehension list

In [2]:
# comprehension list
ll = [i for i in range(10)]
print(ll)
ll = [i for i in range(10) if i % 2 == 0]
print(ll)
ll = [i*2 for i in 'python' if i > 'a' and i < 'p']
print(ll)
print(''.join(ll))
print(', '.join(ll))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
['hh', 'oo', 'nn']
hhoonn
hh, oo, nn

Comprehension dictionary

In [3]:
# comprehension dictionary (zip = iterateur de tuples)
dd = {i: j for i, j in zip(['un', 'deux', 'trois'], range(1, 4))}
print(dd)

# comprehension dictionary (zip = iterateur de tuples)
dd = {i: (j, k) for i, j, k in zip(['un', 'deux', 'trois'],
                                   range(1, 4),
                                   ['one', 'two', 'three', 'four'])}
print(dd)
{'deux': 2, 'trois': 3, 'un': 1}
{'deux': (2, 'two'), 'trois': (3, 'three'), 'un': (1, 'one')}

Générateur

In [4]:
# générateur
gen = (i for i in range(3))
print('generation 1 : ', end='')
for i in gen:
    print(i, '', end='')
print()
print('generation 2 : ', end='')
for i in gen:
    print(i, '', end='')
generation 1 : 0 1 2 
generation 2 : 
In [5]:
def generateur(pch):
    for c in pch:
        yield c  # retourne un générateur
In [6]:
ch = 'python'
print(next(generateur(ch)))
print(next(generateur(ch)))
print('generation 1 : ', end='')
for i in generateur(ch):
    print(i, '', end='')
print()
print('generation 2 : ', end='')
for i in generateur(ch):
    print(i, '', end='')
p
p
generation 1 : p y t h o n 
generation 2 : p y t h o n 
In [7]:
# on parcours le même générateur
myg = generateur(ch)
j = 0
for i in myg:
    print(i, '', end='')
    j += 1
    if j > 3:
        break
print()

for i in myg:
    print(i, '', end='')
print()
p y t h 
o n