List-generated
--A list can be generated quickly , and another listcan be deduced from a list , and the code is simple:
>>> [x * x for x in range (1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x * x for x in range (1, one) if x% 2 = = 0]
[4, 16, 36, 64, 100]
>>> [m + N for M in ' ABC ' for n in ' XYZ ']
[' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']
Generator (Generator)
--with list generation, we can create a list directly. However, the list capacity is limited by memory constraints. Also, if you create a list that contains the elements of the million, it not only takes up a lot of storage space, but if you just need to access the first few elements, then the vast majority of the elements behind it are wasted. In Python , this side loop computes the mechanism, called the generator (Generator).
How to create a generator
- The first method: A list-generated [] change to ()and create a generator:
>>> L = [x * x for x in range (10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range (10))
>>> g
<generator Object <genexpr> at 0x104feab40>
with the next () method of generator, you can print it out individually. Generator saves the algorithm, each time it calls next (), calculates the value of the next element until it is calculated to the last element, no more elements are thrown Stopiteration 's error.
Or:
>>> g = (x * x for x in range (10))
>>> for n in G: ...
Print N
...
0
1
4
9
16
25
36
49
64
81
- The second method: If a function definition contains The yield keyword, then this function is called generator(generator) in Python .
(Fibonacci-Cut series)
Def FAB (max):
N, a, b = 0, 0, 1
While n < max:
Yield b
A, B = B, A + b
n = n + 1
Perform
1 2 3 4 5 6 7 8 9 |
>>> for N in Fab (5): Print n 1 1 2 3 5 |
simply speaking,yieldis to turn a function into aGenerator, withyieldfunction is no longer a normal function,PythonThe interpreter treats it as aGenerator, callingFab (5)does not executeFabfunction instead of returning aiterable Object ! In theForwhen the loop executes, each loop executesFabcode inside the function,Execute toYield bwhen theFabfunction isreturns an iteration value, the next iteration, the code is fromYield bThe next statement continues, and the function's local variable looks exactly the same as before the last break, so the function continues execution until it encountersyield. It looks as if a function is being executed during normal execution.yieldinterrupted several times, each time the interrupt will passyieldreturns the current iteration value.
You can also call Fab (5) manually next () method (because fab (5) generator next () fab execution flow:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
>>> f = Fab (3) >>> F.next () 1 >>> F.next () 1 >>> F.next () 2 >>> F.next () Traceback (most recent): File "<pyshell#62>", line 1, in <module> F.next () Stopiteration |
Python list generation, generator