I. List Production
[ i*2 for i in range(10) ]
Ii. Generator)
The difference between a generator and a list is that the generator data is generated during the call and cannot be sliced like a list.
- Data is generated only when called.
- Only record the current location
Only one"Next"Method
1. Generator 1
>>> ( i*2 for i in range(10) )>>> for i in b:... print(i)
2. Next method of Generator
>>> c = ( i*2 for i in range(10) )>>> c.__next__()0>>> c.__next__()2>>> c.__next__()4
3. Fibonacci Series
# Author:Li Dongfeidef fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return "done"fib(100)
4. Change Fibonacci to a generator.
# Author:Li Dongfeidef fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return "done"f = fib(100)print(f.__next__())print(f.__next__())print(f.__next__())print(f.__next__())print(f.__next__())
5. Capture exceptions
# Author:Li Dongfeidef fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return "done"f = fib(10)while True: try: x = next(f) print('f:', x) except StopIteration as e: print('Generator return value:', e.value) break
6. Generator parallelism (producer consumer model)
# Author: Li dongfeiimport timedef consumer (name): # Consumer While true: baozi = yield print ("steamed stuffed bun [% s], it was eaten by [% s! "% (Baozi, name) def producer (name): # producer c = Consumer (name) C. _ next _ () For I in range (10): time. sleep (1) print ("made 1 steamed stuffed bun! ") C. Send (I) # Sending I to consumer will be accepted by yield and assigned to baoziproducer (" dongfei ")
Iii. iterator)
>>> from collections import Iterable>>> isinstance([],Iterable)True>>> isinstance((),Iterable)True>>> isinstance('abc',Iterable)True
2. Determine whether it is an iterator object.
>>> from collections import Iterator>>> isinstance( ( x for x in range(5) ), Iterator )True
The generator must be an iterator, but not necessarily a generator.
3. Use the ITER () function to convert iterable, such as list, dict, and STR into iterator.
>>> a = [1, 2, 3]>>> b = iter(a)>>> b.__next__()1>>> b.__next__()2>>> b.__next__()3
Iterator and generator 181030