Python function (11)-Generator

Source: Internet
Author: User

First look at what is a list-generated

>>> [i*2 for I in range (][0), 2, 4, 6, 8, ten,,,, 18]>>> a=[]>>> for I in range (10):. ..     A.append (i*2) ...>>> a[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

This code to achieve the effect of three code, this code is a list of generated

List if there is too much data, it takes up a lot of storage space

If you take only some of the data from the list, the storage space used by the other unused data takes up

The generator can also store data, but it only records the current data, and the rest of the data is not generated so that it does not take up too much storage space

How do I create a generator?

>>> [i*2 for I in range (][0), 2, 4, 6, 8, ten,,,, 18]>>> (i*2 for me in range) <generator Object <genexpr> at 0x0000021c9c2e5258>

This is a generator, no data is generated directly.

To fetch one data, a data is generated.

So how do you get the data in the generator?

>>> B = (i*2 for i in range) >>> B<generator object <genexpr> at 0x0000021c9c2e5308>>& Gt;> b.__next__ () 0>>> b.__next__ () 2>>> b.__next__ () 4>>> next (b) 6>>> next (b) 8 >>> Next (b) 10

The generator uses the next () method to get the data, next (b), which is a common method of Python3 and Python2

Python3 can also be used in the __next__ () method, b.__next__ ()

Python2 with Next () method, B.next ()

But it's too cumbersome to take the data again and again using the next () method, so we usually use a for loop to print the data.

>>> C = (i*2 for i in range) >>> for n in C: ...     Print (n) ... 024681012141618

If there is a yield keyword in the function, this function is the generator

#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" def Test (n):    m = 0    b = 0 while    m<n:        print ("Before Yiel D ")        yield b        b = b+3        print (" after yield ")        m =m+1    return" Test Return "a =test (Ten) while True:    try:        B = a.__next__ ()        print ("In the Next", b)    except stopiteration as E:        print (e.value) # Value of Stopiteration is the return value of the generator        exit ()

Run results

Run the process:

The first is to call the test () function

Then execute the while loop

to the __next__ () method, skip to the test () function

After yield is executed, the following statement is not resumed, but the statement after the __next__ () method is returned

Resumes execution of the while loop after executing the statement, executing the __next__ () method

And then jump to the statement after yield

The generator invokes the next () method when it executes, executes to yield in the generator, returns, then executes the statement after the next () method, and then executes to the next () method, jumps to the statement that executes yield, and then executes the yield statement

Implementing single-threaded multiple concurrency with generators

#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" Import timedef Consumer (name):    print ('%s ready to eat Buns '%name) while    True:        baozi = yield        print ('%s bun came, was eaten by%s '% (Baozi,name)) def producer ():    c = Consumer (' Zhang San ')    C2 = Consumer (' John Doe ')    c.__next__ ()    c2.__next__ ()    print (' I'm starting to make buns ') for    I in range:        time.sleep ( 1)        print (' I made 2 buns ')        c.send (' meat ') #调用yield, and pass value        c2.send (' dish ') if __name__ = = ' __main__ ':    producer ()

The Send method can not only call yield, but also the yield value

Run results

Realize the effect of single-thread multiple concurrency

Python function (11)-Generator

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.