Python Builder Generator Introduction

Source: Internet
Author: User
Learning python following Liaoche's blog, and seeing the generator chapter, first mentions Generator, yield, and then in the search for information, and found the concept of the co-process, this article summarizes these concepts.

  generator , literally, is the generator, which is implemented in two ways:

1, is different from the list generator ([]), but with () to represent. (originally this is called generator expression Oh, haha)

Access can be accessed using a for loop, or by using. Next.

N = [' Hello ', ' World ', ' mac ', ' None ']hh = (S.lower () for S in N if Isinstance (s,str) ==true) Print hh#for item in HH: #    Print Item#print hh.next () #print hh.next () #print hh.next () #print Hh.next ()

Output results

<generator Object <genexpr> at 0x7f543a074690>
Hello
World
Apple
None

HH is the value returned by the generator, similar to an array. Supports for loop access and. Next () Access, one thing to note is that the FOR loop cannot execute after the Hh.next (), similar to the pointer to the end, or C + + in the iterator point to the end, and then access to an error occurs.

2. Generate with yield, (called generator function)

Either the next () and the For Loop call, after the yield is executed, the n value is returned, then the current state is suspended and then returned.

def create_counter (n):p rint "Create Counter" #while true:while false:yield nprint ' increment n ' n + = 1cnt = Create_counter (2 ) #print cntfor item in Cnt:print Item#print next (CNT) #print next (CNT) #print cnt.next () #print Cnt.next ()

For example, when printing cnt, <generator object Create_counter at 0x7fa992b8d6e0>

Description This is a, generator.
When false, only the create counter is printed

When True, there is a case of a dead loop with a for loop.

Co-process:

I know there is a concept of process, thread, but what is the association, I really don't know.

from a technical standpoint, "a process is a function that you can pause to execute." If you think of it as "like a generator," then you're right . This is seen in an article.

Python's execution efficiency is high

1, for the sub-program switch is not a thread switch, but by the program itself control, therefore, there is no thread switching overhead, and multithreading ratio, the more threads, the performance advantage of the association is more obvious.

2, the implementation of the process will not involve the locking mechanism.

Attached to a simple example of producer and consumer:

def Consumer (): R = "while true:n = yield rif not N:returnprint (' [Consume        R] Consuming%s ... '% n) time.sleep (1) r = ' OK ' def Produce (c): C.next () n = 0while N < 5: n = n + 1print (' [PRODUCER] producing%s ... '% n) r = c.send (n) print (' [PRODUCER] Consumer return:%s '% r) c.cl OSE () If __name__== ' __main__ ': c = consumer () produce (c) 

1. The consumer function is a generator.
2. C.send (None) is actually equivalent to next (c), the first execution of the execution only to n = yield R stop, and then return the value of R to the caller.
3. Yield R is an expression that is assigned via Send (msg), and send (msg) has a return value, and the return value is: The parameter of the next yield r expression, which is R.
4. Once the produce has been produced, switch to consumer execution via C.send (n). Consumer through yield to get the message, processing, and through yield to return the results. In other words, c.send (1) will not only send a data to C, it will wait for the next yield from C to return a data, it has a return value, one go back to calculate, get the returned data (k OK) to continue the following execution.
5. The entire process is unlocked, executed by one thread, and produce and consumer collaborate to complete the task, so called "co-process", rather than the thread's preemptive multi-tasking.

In summary, yield R is an expression that is assigned by C.send, and then the return value is the next parameter for the yield R expression.

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.