This article describes the Python builder, for more information, see: Python Learning Guide
Objective
With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just access the first few elements, the vast majority of the space behind it is wasted.
python生成器
is used instead of "an array that is not necessarily able to use all elements," and when an element is used, the element is created to save space.
Generator Creation Method The first type:
In the previous we introduced the Python list generation, where we just need to change the list generation to []
()
create a Generatro
>>>L=[x*X forXinch Range(Ten)]>>>l[0,1,4,9, -, -, $, the, -,Bayi, -]>>>G=(x*X forXinch Range(Ten))>>>G<GeneratorObject <genexpr>At0x1022ef630>
The L
g
difference between creation and the outermost []
and ()
, L
is a list, and g
is a generator
We can directly list each element of list (L) in the above expression, but when we print G, we print the type of G, so how do we print every element of generator?
If you want to print out one, you can next()
get the next return value for generator by using a function:
>>>Next(g)0>>>Next(g)1>>>Next(g)4>>>Next(g)9>>>Next(g) ->>>Next(g) ->>>Next(g) $>>>Next(g) the>>>Next(g) ->>>Next(g)Bayi>>>Next(g) Traceback (most recent): File"<stdin>", line1,inch <Module>stopiteration
Generator saves the algorithm, each time it is called next(g)
, computes g
the value of the next element, knowing that the last element is calculated, and no more elements are thrown when StopIteration
the error occurs.
This constant invocation next(g)
is so perverted that the generator is an iterative object
>>>fromimport Iterable #载入模块>>>isinstance(g, Iterable) #生成器是可迭代对象吗?True
So, you know what to use?
Of course, using powerful for...in
iterations to achieve
>>>=*forinrange(10))>>>forin g: print(n)0149162536496481
Iterate through for
the generators and don't care about StopIteration
the errors.
Use the keyword yield keyword
Generator is very powerful. If the calculated algorithm is more complex, and the loop with similar list generation for
cannot be implemented, it can also use functions to implement
Fibonacci Sequence Generator
defCreatnum ():Print("---Start execution of the generator method---") A, B= 0,1 forIinch Range(0,5):Print("--step1--")yieldBPrint("--step2--") A, B=B,a+BPrint("--step3--")Print("--stop--")Print("Call method directly ...")Print(Creatnum ())#这里用一个标识符来指向生成器 (Do not take creatnum () as a function)Func=Creatnum ()#使用for循环来执行生成器 forIinchFuncPrint(i) Output: (Does not crash after execution)#直接调用方法...<GeneratorObjectCreatnum at0X101C30F10>---To begin the execution of a generator method-----Step1--1--Step2----Step3----Step1--1--Step2----Step3----Step1--2--Step2----Step3----Step1--3--Step2----Step3----Step1--5--Step2----Step3----Stop--
The
can use the builder when executing the generator. Send (param) method
The Send method does not just perform a step next operation, but also passes the parameters in the send to the generator to act as the return value of the yield expression
def test(): i = 0 while i < 5: temp = yield i print(temp) i += 1t = test()#先使用next执行,看能出来什么结果t.__next__()t.__next__()print(t.__next__())#使用send执行t.send("1231231231223123")print(t.send("hahahahhahaha"))输出结果: (可见next输出temp为none , 而send 则把值传递进了生成器)NoneNone21231231231223123hahahahhahaha4
Reference
- How the Python generator works
- The yield keyword in python
- Python Builder
- Liaoche-Generator
Python List Builder