Python yield and yield from usage summary

Source: Internet
Author: User
Tags iterable

#例1. The number of first N in a simple output Fibonacci array
#缺点: The function is not reusable because the FAB function returns None, and the other function cannot get the sequence generated by the function
#要提高 the reusability of the Fab function, it is best not to print the columns directly but to return a list.
def FAB1 (max):
N, a, b = 0, 0, 1
While n < max:
Print (b,end= ")
A, B = B, A + b
n = n + 1
FAB1 (5)

#例 2.
#缺点: The memory consumed by this function will increase as the parameter max increases, and if you want to control memory consumption,
#最好不要用 List to hold intermediate results, but to iterate through Iterable objects
def FAB2 (max):
N, a, b = 0, 0, 1
L = []
While n < max:
L.append (b)
A, B = B, A + b
n = n + 1
Return L

#例3
#说明: A function with yield is no longer a normal function, and the Python interpreter treats it as a generator,
#调用 Fab (5) does not execute the FAB function, but returns a Iterable object!
#在 the For loop executes, each loop executes the code inside the FAB function, and when it executes to yield B, the FAB function returns an iteration value.
#下次迭代时, the code continues execution from the next statement in yield B, and the local variable of the function looks exactly the same as before the last break execution.
#于是函数继续执行 until the yield is met again.
def FAB3 (max):
N, a, b = 0, 0, 1
While n < max:
Yield b
# Print B
A, B = B, A + b
n = n + 1
F=FAB3 (5)
Print ("F is an iterative object, and no function is executed")
Print (f)
Print (' Fab3 returns a Iterable object that can be used for loop to get the value ')
For N in F:
Print (n)

#例4: #说明: Yield from iterable is essentially equal to the abbreviated version of the for item in Iterable:yield item    def f_wrapper1 (f): For    G in  F:        Yield gwrap = F_wrapper1 (FAB3 (5)) for I in Wrap:    print (i,end= ") print (' \ n use yield from instead of For Loop ') def f_wrapper2 (f ):     yield from F # Note here must be a generated object wrap = F_wrapper2 (FAB3 (5)) for I in Wrap:    print (i,end= ") print (' \ n---------------------') print (' yield from contains multiple subroutines ') def g (x):    yield from range (x, 0,-1)    yield from range (x) Print (List (g (5))) for G in  G (6): Print (    g,end= ', ')        print (' \ n---------------------')  
Note that the red part is the replacement part, andyield from iterable is essentially equal to the abbreviated version of the for item in Iterable:yield item

#例5 use the yield from statement to transfer data to the generator (coprocessor) #传统的生产者-The consumer model is a thread-write message, a thread that takes messages, controls the queue through a lock mechanism, and waits, but can be accidentally deadlocked. #如果改用协程, producer production news, directly through the yield jump to the consumer began to execute, until the completion of the consumer, to return to the producer continued production, efficiency is extremely high: def consumer_work (len): # Read the data sent in, and simulate processing data prin T ("Writer:") w= "while true:w = Yield W # W receives the data sent in, and also returns the data print (' [CONSUMER] consuming%s. .>> ', W) w*=len #将返回的数据乘以100 Time.sleep (0.1) def consumer (Coro): Yield from coro# passing data to a co-process (Generator) object         def produce (c): C.send (None) # "Prime" the Coroutine for I in range (5): print (' [produce] producing%s----', i) W=c.send (i) #发送完成后进入协程中执行 print (' [Produce] receive%s----', W) c.close () c1=consumer_work () Produce ( Consumer (C1))

Execution Result:
Writer
[Produce] Producing%s----0
[CONSUMER] Consuming%s...>> 0
[Produce] receive%s----0
[Produce] Producing%s----1
[CONSUMER] Consuming%s...>> 1
[Produce] receive%s----100
[Produce] Producing%s----2
[CONSUMER] Consuming%s...>> 2
[Produce] receive%s----200
[Produce] Producing%s----3
[CONSUMER] Consuming%s...>> 3
[Produce] receive%s----300
[Produce] Producing%s----4
[CONSUMER] Consuming%s...>> 4
[Produce] receive%s----400

Yield from the general grasp of these two usages can be;

Python yield and yield from usage summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.