- list comprehension
a=[i*2 for i in range(10)] print(a) >>> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
- Iterators & Generators
generator:
With list comprehensions, we can directly create a list. However, due to memory constraints, the list capacity is definitely limited. Moreover, creating a list with 1 million elements not only takes up a lot of storage space, but if we only need to access the first few elements, then most of the space occupied by the latter elements will be wasted.
So, if the list elements can be calculated according to a certain algorithm, can we continue to calculate the subsequent elements in the process of looping? This saves a lot of space by not having to create a complete list . In Python, this mechanism of computing while looping is called a generator.
Corresponding data is only generated when called
method one:
a=[i*2 for i in range(10)] print(a) >>>
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Change a list []
comprehension to()
a=(i*2 for i in range(10)) print(a) >>> <generator object <genexpr> at 0x05482570>
Calling method: a.__next()__
print(next(a)) print(next(a)) >>> 0 2
or
for i in a: print(i) >>> 0 2 4 6 8 10 12 14 16 18
Method Two:
Fibonacci sequence (Fibonacci): Any number except the first and second numbers can be obtained by adding the first two numbers
def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'done'
Assignment statement:
a, b = b, a + b
is equivalent to:
t = (b, a + b) # t is a tuple a = t[0] b = t[1]
Change the print(b) in the function to yield b
become a generator
def fib(max): n,a,b = 0,0,1 while n < max: #print(b) yield b a,b = b,a+b n += 1 return 'done' f=fib(5) print(f) print(f.__next__()) print(f.__next__()) print(f.__next__()) print(f.__next__()) >>> <generator object fib at 0x05792570> 1 1 2 3
for i in f: print(i) >>> 1 1 2 3 5
But for
when the generator is called with a loop, it is found that the return value of the generator's return
statement cannot be obtained. If you want to get the return value, you must catch the StopIteration
error, and the return value is contained StopIteration
in value
:
g = fib(6) while True: try: x = next(g) print('g:', x) except StopIteration as e: print('Generator return value:', e.value) break >>> g: 1 g: 1 g: 2 g: 3 g: 5 Generator return value: done
- iterator