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])
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))
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)
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='')
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='')
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()